In: Computer Science
This function will receive a list of elements with duplicate elements, this function should remove the duplicate elements in the list and return a list without duplicate elements. The elements in the returned list must be in the same order that they were found in the list the function received. A duplicate element is an element found more than one time in the specified list.
JAVA
If you have any problem with the code feel free to comment.
Program
import java.util.ArrayList;
import java.util.function.Predicate;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(1);
list.add(5);
list.add(2);
list.add(4);
list.add(2);
System.out.println("Duplicate list: " + list);
System.out.println("Non duplicate list: " + removeDuplicates(list));
}
public static <T> ArrayList<T> removeDuplicates(ArrayList<T> list) {
ArrayList<T> newList = new ArrayList<>(list);
// replacing the duplicate items with null
for (T item : newList) {
if (item == null)
continue;
int count = 0;
for (int i = 0; i < newList.size(); i++) {
if (item.equals(newList.get(i)))
count++;
if (item.equals(newList.get(i)) && count > 1) {
newList.set(i, null);
}
}
}
// removing all null values from the list
newList.removeIf((Predicate<T>) ((t) -> t == null));
return newList;
}
}
Output