In: Computer Science
Java Programming
CS 209 Data Structure
1. Create a method that takes an ArrayList of String and returns a copy of that ArrayList with no duplicates.
The relative ordering of elements in the new ArrayList should be the same.
Sample Input: {"qwerty", "asdfgh", "qwer", "123", "qwerty", "123", "zxcvbn", "asdfgh"}
Sample Output: {"qwerty", "asdfgh", "qwer", "123", "zxcvbn"}
import java.util.*;
public class Main
{
public static void main(String[] args) {
// Get the ArrayList with duplicate
values
ArrayList<String>
list = new ArrayList<>(
Arrays
.asList("qwerty", "asdfgh", "qwer", "123", "qwerty", "123",
"zxcvbn", "asdfgh"));
// Print the Arraylist
System.out.println("ArrayList with duplicates: "
+ list);
// Remove duplicates
ArrayList<String>
newList = removeDuplicates(list);
// Print the ArrayList with duplicates removed
System.out.println("ArrayList with duplicates removed: "
+ newList);
}
// 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;
}
}