List difference in java

前端 未结 11 1784
野的像风
野的像风 2020-11-30 04:33

I have two ArrayList as follows:

original: 12, 16, 17, 19, 101

selected: 16, 19, 107, 108, 109

11条回答
  •  醉酒成梦
    2020-11-30 05:00

    Here is a function to find intersection of various collections (more than 2) -

    public static > C findIntersection(C newCollection,
                                                                Collection... collections) {
      boolean first = true;
      for (Collection collection : collections) {
          if (first) {
              newCollection.addAll(collection);
              first = false;
          } else {
              newCollection.retainAll(collection);
          }
      }
      return newCollection;
    }
    

    Usage -

    public static void main(String[] args) {
      List l1 = List.of(1, 3, 5, 7, 9, 11, 13);
      List l2 = List.of(1, 2, 3, 5, 8, 13);
      List l3 = List.of(2, 3, 5, 7, 11, 13);
      Set intersection = findIntersection(new HashSet<>(), l1, l2, l3);
      System.out.println(intersection);
     }
    

提交回复
热议问题