Efficient intersection of two List in Java?

后端 未结 8 578
南方客
南方客 2020-11-28 12:23

Question is simple:

I have two List

List columnsOld = DBUtils.GetColumns(db, TableName);
List columnsNew = DBUtils.GetCol         


        
8条回答
  •  执念已碎
    2020-11-28 13:00

    There is a nice way with streams which can do this in one line of code and you can two lists which are not from the same type which is not possible with the containsAll method afaik:

    columnsOld.stream().filter(c -> columnsNew.contains(c)).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());
    

提交回复
热议问题