Common elements in two lists

后端 未结 14 1030
无人共我
无人共我 2020-11-22 12:22

I have two ArrayList objects with three integers each. I want to find a way to return the common elements of the two lists. Has anybody an idea how I can achiev

14条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 12:44

    Using Java 8's Stream.filter() method in combination with List.contains():

    import static java.util.Arrays.asList;
    import static java.util.stream.Collectors.toList;
    
    /* ... */
    
    List list1 = asList(1, 2, 3, 4, 5);
    List list2 = asList(1, 3, 5, 7, 9);
    
    List common = list1.stream().filter(list2::contains).collect(toList());
    

提交回复
热议问题