简体   繁体   English

使用isPresent方法在Java8中列出过滤器

[英]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. 我想迭代列表与另一个String比较。 Only if another String doesn't match with any element in the list, then I should enter the loop. 只有当另一个String与列表中的任何元素不匹配时,我才应该进入循环。 I tried something like below, but it didn't worked. 我尝试了类似下面的东西,但它没有用。 Any other alternate approach to do the same in Java 8? 在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. 因此,为了避免ConcurrentModificationException ,我使用if条件进行验证。

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() 你应该使用noneMatch()

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

You should be using Stream#noneMatch for this. 您应该使用Stream#noneMatch 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 另外,尽量避免在if语句中加入太多逻辑,在可读变量中提取max

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. 可以在不使用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");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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