4 回答
TA贡献1712条经验 获得超3个赞
假设您有一个包含所有状态代码的列表,您可以使用流过滤器,即
List<Integer> httpCodes;
String prefix = "5"
List<Integer> filteredResults = httpCodes.stream().filter(value -> value.toString().startsWith(prefix)).collect(Collectors.toList());
TA贡献1757条经验 获得超7个赞
我可能会这样做:
public void getHttpStatus(Integer httpStatus){
int numberOfDigits = (int) (Math.log10(number) + 1);
int minStatus = httpStatus * ((int) Math.pow(10, 3 - numberOfDigits));
int maxStatus = (httpStatus + 1) * ((int) Math.pow(10, 3 - numberOfDigits)) - 1
messageRepository.findByHttpStatusBetween(minStatus,maxStatus)
}
或者你可以这样做,
String status= httpStatus.toString();
String startIndex = status;
String endIndex = status;
if ( status.length() == 1 )
{
startIndex = status + "00";
endIndex = status + "99";
}
else if ( status.length() == 2 )
{
startIndex = status + "0";
endIndex = status + "9";
}
int sIndex = Integer.parseInt( startIndex );
int eIndex = Integer.parseInt( endIndex );
messageRepository.findByHttpStatusBetween(sIndex, eIndex);
TA贡献1765条经验 获得超5个赞
public class Range {
public int lb;
public int ub;
public Range(int lb, int ub) {
this.lb = lb;
this.ub = ub;
}
public Range(int statusCode) {
int length = (int) (Math.log10(statusCode) + 1);
if (length == 0 || length > 2) {
throw new RuntimeException("Cant parse status code of invald length: " + length);
}
if (length == 1) {
this.lb = statusCode * 100;
this.ub = ((statusCode + 1) * 100) - 1;
} else {
this.lb = statusCode * 10;
this.ub = ((statusCode + 1) * 10) - 1;
}
}
}
public class Main {
public static void main(String[] args) {
Range r1 = new Range(52);
Range r2 = new Range(2);
Range r3 = new Range(20);
System.out.println("Lowerbound: " + r1.lb);
System.out.println("Upperbound: " + r1.ub);
System.out.println("Lowerbound: " + r2.lb);
System.out.println("Upperbound: " + r2.ub);
System.out.println("Lowerbound: " + r3.lb);
System.out.println("Upperbound: " + r3.ub);
}
}
输出如下:
Lowerbound: 520
Upperbound: 529
Lowerbound: 200
Upperbound: 299
Lowerbound: 200
Upperbound: 209
不检查特殊值 0。
然后你的函数可以重构为:
public void getHttpStatus(Integer httpStatus){
Range r = new Range(httpStatus.intValue());
messageRepository.findByHttpStatusBetween(r.lb, r.ub);
}
添加回答
举报