Intersection and union of ArrayLists in Java

后端 未结 24 2680
离开以前
离开以前 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

    Here is a way how you can do an intersection with streams (remember that you have to use java 8 for streams):

    List fooList1 = new ArrayList<>(Arrays.asList(new foo(), new foo()));
    List fooList2 = new ArrayList<>(Arrays.asList(new foo(), new foo()));
    fooList1.stream().filter(f -> fooList2.contains(f)).collect(Collectors.toList());
    

    An example for lists with different types. If you have a realtion between foo and bar and you can get a bar-object from foo than you can modify your stream:

    List fooList = new ArrayList<>(Arrays.asList(new foo(), new foo()));
    List barList = new ArrayList<>(Arrays.asList(new bar(), new bar()));
    
    fooList.stream().filter(f -> barList.contains(f.getBar()).collect(Collectors.toList());
    

提交回复
热议问题