Check if one list contains element from the other

前端 未结 12 2632
没有蜡笔的小新
没有蜡笔的小新 2020-11-30 20:45

I have two lists with different objects in them.

List list1;
List list2;

I want to check if element from list

12条回答
  •  佛祖请我去吃肉
    2020-11-30 21:41

    If you just need to test basic equality, this can be done with the basic JDK without modifying the input lists in the one line

    !Collections.disjoint(list1, list2);
    

    If you need to test a specific property, that's harder. I would recommend, by default,

    list1.stream()
       .map(Object1::getProperty)
       .anyMatch(
         list2.stream()
           .map(Object2::getProperty)
           .collect(toSet())
           ::contains)
    

    ...which collects the distinct values in list2 and tests each value in list1 for presence.

提交回复
热议问题