How to select duplicate values from a list in java?

后端 未结 13 932
傲寒
傲寒 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:26

    Your List should ideally have been a Set which doesn't allow duplicates in the first place. As an alternative to looping, you could either convert and switch to Set or use it intermediately to eliminate duplicates as follows:

    List dupesList = Arrays.asList(4L, 6L, 6L, 7L, 7L, 8L);
    
    Set noDupesSet = new HashSet(dupesList);
    System.out.println(noDupesSet); // prints: [4, 6, 7, 8]
    
    // To convert back to List
    Long[] noDupesArr = noDupesSet.toArray(new Long[noDupesSet.size()]);
    List noDupesList = Arrays.asList(noDupesArr);
    System.out.println(noDupesList); // prints: [4, 6, 7, 8]
    

提交回复
热议问题