Reputation: 3
I have a declaration of a ArrayList T
ArrayList<Integer> T = new ArrayList<Integer>();
And i have a while loop which should be active until the list will be composed of only -1 int's. Currently it looks like this:
while(T.contains(!-1))
As you probably guessed it. It does not work properly since i can't use negation on a integer.
Upvotes: 0
Views: 54
Reputation: 1676
If you want to repetitively check whether there are elements that are not -1 in the list, you can do it as below for efficiency:
n
while (n > 0) { do stuff; and decrease n if the value of an element becomes -1 }
Upvotes: 0
Reputation: 131346
But the loop has to end only if the ENTIRE list is made of -1's.
You could use a HashSet
that will remove all duplicated elements in the List.
if the HashSet
object has a size of 1 (it means that the list contains only the same value) and if the first element of the list is -1
, it means that the list contains only -1
values.
List<Integer> integers = new ArrayList<Integer>();
while (!(new HashSet<Integer>(integers).size() == 1 && integers.get(0).intValue() == -1)){
....
}
Upvotes: 0
Reputation: 48258
you can stream the list:
List<Integer> myList = ...;
myList = myList.stream().filter(x -> x < 0).collect(Collectors.toList());
System.out.println(myList);
Upvotes: 0
Reputation: 56423
You can use Stream#allMatch
.
while(!T.stream().allMatch(i -> i == -1)){ // note the ! operator to negate the result
//do something
}
This should keep looping until the list will be composed of only -1
ints as you've suggested.
Upvotes: 2