I have developed an array list.
ArrayList list = new ArrayList();
list.add(\"1\");
list.add(\"2\");
list.add(\"3\");
list.add(\"
Just use the normal constructor:
ArrayList<T> yourList;
HashSet<T> set = new HashSet<T>(yourList);
And you'll have a new view of the items, with duplicates removed, but you will lose ordering. This is true in every answer posted so far. To keep ordering you should iterate on the existing list and remove an element only if it's a duplicate (which can be done using a set to check if an element was already found).
You can use a set in the first place or convert into it:
Set<String> set = new TreeSet<String>(list);
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.
Here are some way you can achieve this.
Using Java 8:
List<String> distinctLambda=originalList.stream()
.distinct().collect(Collectors.toList());
System.out.println(distinctLambda);
Using Set:
Set<String> distinctSet=new HashSet<>(originalList);
System.out.println(distinctSet);
Normal for loop:
List<String> distinctNewList=new ArrayList<>();
for (String temp:originalList) {
if(distinctNewList.size()==0){
distinctNewList.add(temp);
continue;
}
if(!distinctNewList.contains(temp)){
distinctNewList.add(temp);
}
}
System.out.println(distinctNewList);
Here is your data set:
ArrayList<String> originalList = new ArrayList<>();
originalList.add("1");
originalList.add("2");
originalList.add("3");
originalList.add("3");
originalList.add("5");
originalList.add("6");
originalList.add("7");
originalList.add("7");
originalList.add("1");
originalList.add("10");
originalList.add("2");
originalList.add("12");
If you need to preserve elements order then use LinkedHashSet instead of HashSet
Set<String> mySet = new LinkedHashSet<String>(list);
Java 8 way:
list.stream().distinct().collect(Collectors.toList());
done :)