// Java program to remove duplicates from ArrayList
import java.util.*;
public class GFG {
// Function to remove duplicates from an ArrayList
public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list)
{
// Create a new ArrayList
ArrayList<T> newList = new ArrayList<T>();
// Traverse through the first list
for (T element : list) {
// If this element is not present in newList
// then add it
if (!newList.contains(element)) {
newList.add(element);
}
}
// return the new list
return newList;
}
// Driver code
public static void main(String args[])
{
// Get the ArrayList with duplicate values
ArrayList<Integer>
list = new ArrayList<>(
Arrays
.asList(1, 10, 1, 2, 2, 3, 3, 10, 3, 4, 5, 5));
// Print the Arraylist
System.out.println("ArrayList with duplicates: "
+ list);
// Remove duplicates
ArrayList<Integer>
newList = removeDuplicates(list);
// Print the ArrayList with duplicates removed
System.out.println("ArrayList with duplicates removed: "
+ newList);
}
}
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
public class ArrayDuplicate {
public static void main(String args[]) {
List<Integer> num = new ArrayList<Integer>();
num.add(1);
num.add(2);
num.add(3);
num.add(4);
num.add(5);
num.add(6);
num.add(3);
num.add(4);
num.add(5);
num.add(6);
System.out.println("Your list of elements in ArrayList : " + num);
Set<Integer> primesWithoutDuplicates = new LinkedHashSet<Integer>(num);
num.clear();
num.addAll(primesWithoutDuplicates);
System.out.println("list of original numbers without duplication: " + num);
}
}
Set<String> set = new HashSet<>(yourList);
yourList.clear();
yourList.addAll(set);
ArrayList<Object> withDuplicateValues;
HashSet<Object> withUniqueValue = new HashSet<>(withDuplicateValues);
withDuplicateValues.clear();
withDuplicateValues.addAll(withUniqueValue);
// remove duplicates with HashSet
Set<Song> songSet = new HashSet<>(songList);
System.out.println("6: " + songSet);
// TreeSet, remove duplicates and keep it sorted
Set<Song> songTreeSet = new TreeSet<>(songList);
System.out.println("7: " + songTreeSet);
// TreeSet can accept Comparator, pass it in its constructor
Set<Song> songTreeSetComparator = new TreeSet<>((o1, o2) -> o1.getBpm() - o2.getBpm());
songTreeSetComparator.addAll(songList);
System.out.println("8: (sort by BPM)" + songTreeSetComparator);