How to select duplicate values from a list in java?

后端 未结 13 826
傲寒
傲寒 2021-01-18 00:38

For example my list contains {4, 6, 6, 7, 7, 8} and I want final result = {6, 6, 7, 7}

One way is to loop through the list and eliminate unique values (4, 8 in this

13条回答
  •  囚心锁ツ
    2021-01-18 01:11

    I like answer Java 8, Streams to find the duplicate elements. Solution return only unique duplicates.

     Integer[] numbers = new Integer[] { 1, 2, 1, 3, 4, 4 };
     Set allItems = new HashSet<>();
     Set duplicates = Arrays.stream(numbers)
        .filter(n -> !allItems.add(n)) //Set.add() returns false if the item was already in the set.
        .collect(Collectors.toSet());
     System.out.println(duplicates); // [1, 4]
    

提交回复
热议问题