简体   繁体   中英

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");
}

You should use noneMatch()

if (mylist.stream().noneMatch(str -> str.equalsIgnoreCase(testString))) {
    System.out.println("Value is not Present");
}

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");
}

The above can be achieved without using the Stream API. Below is a possible solution

String searchValue = "COW";
List<String> list = Arrays.asList("CAT", "DOG");

if(!list.contains(searchValue)){
    System.out.println("Value is not Present");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM