How to select duplicate values from a list in java?

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

    Some good answers so far but another option just for the fun of it. Loop through the list trying to place each number into a Set e.g. a HashSet. If the add method returns false you know the number is a duplicate and should go into the duplicate list.

    EDIT: Something like this should do it

    Set unique = new HashSet<>();
    List duplicates = new ArrayList<>();
    for( Number n : inputList ) {
        if( !unique.add( n ) ) {
            duplicates.add( n );
        }
    }
    

提交回复
热议问题