Intersection and union of ArrayLists in Java

后端 未结 24 2534
离开以前
离开以前 2020-11-22 06:05

Are there any methods to do so? I was looking but couldn\'t find any.

Another question: I need these methods so I can filter files. Some are AND filter

24条回答
  •  无人共我
    2020-11-22 06:49

    This post is fairly old, but nevertheless it was the first one popping up on google when looking for that topic.

    I want to give an update using Java 8 streams doing (basically) the same thing in a single line:

    List intersect = list1.stream()
        .filter(list2::contains)
        .collect(Collectors.toList());
    
    List union = Stream.concat(list1.stream(), list2.stream())
        .distinct()
        .collect(Collectors.toList());
    

    If anyone has a better/faster solution let me know, but this solution is a nice one liner that can be easily included in a method without adding a unnecessary helper class/method and still keep the readability.

提交回复
热议问题