0

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.

6
  • T.contains(!-1)??? what does that suppose to mean? Commented May 31, 2017 at 15:34
  • the problem is that you are using "!" on the wrong place, the wile loop works with condition, and the condition you need it that "not contains", try putting the "!" before your condition Commented May 31, 2017 at 15:34
  • Yeah if i use negation on while(!T.contains(-1)) the loop will end after FIRST -1 int lands into T. But the loop has to end only if the ENTIRE list is made of -1's. Commented May 31, 2017 at 15:36
  • Voting to close as a typographical error Commented May 31, 2017 at 15:36
  • @melli-182 not sure that'll fix it, he wants to run the while loop until the list contains only -1s. and contains() won't help there. Commented May 31, 2017 at 15:36

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that seems to fix my problems.
0

you can stream the list:

List<Integer> myList = ...;
myList = myList.stream().filter(x -> x < 0).collect(Collectors.toList());
System.out.println(myList);

Comments

0

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)){
     ....
 }

Comments

0

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:

  1. Count the number of elements that are not -1 and store this value in n
  2. while (n > 0) { do stuff; and decrease n if the value of an element becomes -1 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.