Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
408 views
in Technique[技术] by (71.8m points)

java - Removing duplicate elements from a List

I have developed an array list.

ArrayList<String> list = new ArrayList<String>();

list.add("1");
list.add("2");
list.add("3");
list.add("3");
list.add("5");
list.add("6");
list.add("7");
list.add("7");
list.add("1");
list.add("10");
list.add("2");
list.add("12");

But as seen above it contains many duplicate elements. I want to remove all duplicates from that list. For this I think first I need to convert the list into a set.

Does Java provide the functionality of converting a list into a set? Are there other facilities to remove duplicates from a list?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can convert to a Set with:

Set<String> aSet = new HashSet<String>(list);

Or you can convert to a set and back to a list with:

list = new ArrayList<String>(new HashSet<String>(list));

Both of these, however, are not likely to preserve the order of the elements. To preserve order, you can use a HashSet as an auxiliary structure while iterating:

List<String> list2 = new ArrayList<String>();
HashSet<String> lookup = new HashSet<String>();
for (String item : list) {
    if (lookup.add(item)) {
        // Set.add returns false if item is already in the set
        list2.add(item);
    }
}
list = list2;

In the case of duplicates, only the first occurrence will appear in the result. If you want only the last occurrence to appear, that's a tougher problem. I'd tackle it by reversing the input list, applying the above, and then reversing the result.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...