简体   繁体   English

列表与重复项没有重复

[英]List with duplicates to without duplicates

I have a list with duplicate values. 我有一个重复值的列表。

List<valFile> isList = valBo.findId();

isList has values like {100, 100, 100, 102, 105, 105} isList的值类似于{100,100,100,102,105,105}

I want to remove these duplicates and use the same list with no duplicates. 我想删除这些重复项并使用相同的列表,没有重复。 I tried set but dont know how to use the same list without duplicates. 我试过设置,但不知道如何使用相同的列表,没有重复。

Create a LinkedHashSet to maintain the ordering and add all the items from the List. 创建LinkedHashSet以维护排序并添加List中的所有项目。 The duplicates will be discarded: 重复项将被丢弃:

Set<valFile> set = new LinkedHashSet<valFile>(isList);

Then add it back to a list: 然后将其添加回列表:

List<valFile> listWithoutDuplicates = new ArrayList<valFile>(set);

I would use a set and dump back to a list. 我会使用一个集合并转储回列表。

List<valFile> unique = new ArrayList<valFile>(new HashSet<valFile>(islist));
Collections.sort(unique);

Or if you have a good comparator, you can use a TreeSet 或者如果你有一个好的比较器,你可以使用TreeSet

Set<valFile> unique = new TreeSet<valFile>(isList);

If you absolutely MUST use the same list (perhaps because there are other references to it somewhere), your best bet is to clear it. 如果你绝对必须使用相同的列表(也许是因为在某处有其他参考),你最好的办法是清除它。

List<valFile> unique = new ArrayList<valFile>(new HashSet<valFile>(islist));
Collections.sort(unique);
isList.clear();
isList.addAll(unique);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM