如何从java中的列表中选择重复值? [英] How to select duplicate values from a list in java?

查看:148
本文介绍了如何从java中的列表中选择重复值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如我的列表包含{4,6,6,7,7,8},我希望最终结果= {6,6,7,7}

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

一种方法是循环遍历列表并消除唯一值(在这种情况下为4,8)。

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

有没有其他有效的方法而不是循环列表?我问过这个问题,因为我工作的清单非常大?
我的代码是

Is there any other efficient way rather than looping through list ? I asked this question because the list that I am working is very large ? My code is

List<Long> duplicate = new ArrayList();
for (int i = 0; i < list.size(); i++) {
     Long item = (Long) list.get(i);
     if (!duplicate.contains(item)) {
          duplicate.add(item);
         }
     }


推荐答案

一些到目前为止很好的答案,但另一种选择只是为了它的乐趣。在列表中循环,尝试将每个数字放入一个Set中,例如 HashSet 。如果add方法返回false,你知道该数字是重复的,应该进入重复列表。

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.

编辑:这样的事情应该这样做

Something like this should do it

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

这篇关于如何从java中的列表中选择重复值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆