I am going to design a method which receives an arraylist that contains n of class a. In addition, it will receives two variables start and end . i want to test this condition for those classes between start and end variables. for example, if start = 5 and end = 12 . i want to check if the classes { 5, 6,7,8,9,10,11,12} achieve this condition or not
This is part of my code
static void checkDonothing(ArrayList<tt> Result , int condations, int start, int end){
for(int i = 0; i<Result.size(); i++){
if ( Result.get(i).number >= start && Result.get(i).number <=end){
//// do action
}
}
}
I want to do the action if the condation is true for all these classes btween end and start.
Do you have any suggestion to do that ?
答案 0 :(得分:0)
Reverse your condition and return
if it passes. Otherwise do the action after the loop.
static void checkDonothing(ArrayList<tt> Result , int condations, int start, int end){
for(int i = 0; i<Result.size(); i++){
if (!(Result.get(i).number >= start && Result.get(i).number <=end)){
// Note the ! (not) added in the condition to reverse it.
return;
}
}
// If it arrives here, your condition has passed for all.
// So, do the action.
}
答案 1 :(得分:0)
如果你正在使用Java 8,你可以这样做:
static void checkDonothing(ArrayList<tt> Result , int condations, int start, int end){
boolean doAction = Result.stream().limit(end).skip(start)
.allMatch(obj -> obj.equals(condations)/*write your custom condition here*/);
if(doAction)
{
//Do action
}
}