What is the best way to filter a Java Collection?

后端 未结 27 3336
故里飘歌
故里飘歌 2020-11-21 06:55

I want to filter a java.util.Collection based on a predicate.

27条回答
  •  长情又很酷
    2020-11-21 07:35

    How about some plain and straighforward Java

     List list ...;
     List newList = new ArrayList<>();
     for (Customer c : list){
        if (c.getName().equals("dd")) newList.add(c);
     }
    

    Simple, readable and easy (and works in Android!) But if you're using Java 8 you can do it in a sweet one line:

    List newList = list.stream().filter(c -> c.getName().equals("dd")).collect(toList());
    

    Note that toList() is statically imported

提交回复
热议问题