I have one list which contains some String values. I want to iterate the list comparing with another String. Only if another String doesn't match with any element in the list, then I should enter the loop. I tried something like below, but it didn't worked. Any other alternate approach to do the same in Java 8?
Note: In the loop I'm adding some more elements to the same list. Hence, to avoid ConcurrentModificationException
, I'm using a if-condition for my validation.
List<String> mylist = new ArrayList<>();
mylist.add("test");
mylist.add("test1");
if(mylist.stream()
.filter(str -> !(str.equalsIgnoreCase("test")))
.findFirst()
.isPresent()) {
System.out.println("Value is not Present");
}
public boolean isPresent() Return true if there is a value present, otherwise false . Returns: true if there is a value present, otherwise false.
ArrayList contains() method in Java is used for checking if the specified element exists in the given list or not. Returns: It returns true if the specified element is found in the list else it returns false.
You can filter Java Collections like List, Set or Map in Java 8 by using the filter() method of the Stream class. You first need to obtain a stream from Collection by calling stream() method and then you can use the filter() method, which takes a Predicate as the only argument.
You should be using Stream#noneMatch
for this. It will make your code more readable and more concise. Also, try to avoid putting to much logic inside of your if statement, extract a max in readable variables
List<String> mylist = new ArrayList<>();
mylist.add("test");
mylist.add("test1");
Predicate<String> equalsIgnoreCasePredicate = str -> str.equalsIgnoreCase("test");
boolean noneMatchString = mylist.stream().noneMatch(equalsIgnoreCasePredicate);
if (noneMatchString) {
System.out.println("Value is not Present");
}
You should use noneMatch()
if (mylist.stream().noneMatch(str -> str.equalsIgnoreCase(testString))) {
System.out.println("Value is not Present");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With