Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List filter in Java8 using isPresent method

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");
}
like image 750
Prasad Avatar asked Mar 23 '19 10:03

Prasad


People also ask

What is isPresent () in Java?

public boolean isPresent() Return true if there is a value present, otherwise false . Returns: true if there is a value present, otherwise false.

How do you check if a value is present in a list in Java 8?

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.

How will you run a filter on a collection?

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.


2 Answers

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");
}
like image 97
Yassin Hajaj Avatar answered Sep 28 '22 13:09

Yassin Hajaj


You should use noneMatch()

if (mylist.stream().noneMatch(str -> str.equalsIgnoreCase(testString))) {
    System.out.println("Value is not Present");
}
like image 38
Nicholas Kurian Avatar answered Sep 28 '22 14:09

Nicholas Kurian