Given below code and implement your method (my_method) which will remove the duplicates and sort the list.
Given following conditions
import java.io.*;
import java.util.*;
class Solution {
public static void main(String[] args) {
List strings = new ArrayList();
strings.add("Hello, World!");
strings.add("Welcome to CodeWorld.");
strings.add("This is an example");
strings.add("Hello, World!");
strings.add("Welcome to CodeWorld.");
strings.add("This is an example");
strings.add("Hello, World!");
strings.add("Welcome to CodeWorld.");
strings.add("This is an example");
strings.add("Hello, World!");
strings.add("Welcome to CodeWorld.");
strings.add("This is an example");
my_method(strings);
for (Object string : strings) {
System.out.println(string);
}
}Find below my solution.
private static void my_method(List list){
//Sort the list
Object[] a = list.toArray();
Arrays.sort(a);
ListIterator i = list.listIterator();
HashSet set = new HashSet<>();
for (int j=0; j< list.size(); j++) {
if(!set.contains(a[j])){//Remove duplicate
i.next();
i.set(a[j]);
}
set.add(a[j]);
}
while(i.hasNext()){
i.next();
i.set(null);//Assign null to remaining values
}
}Expected output
Hello, World!
This is an example
Welcome to CodeWorld.
null
null
null
null
null
null
null
null
nullPlease feel free to add your suggestions/improvements to this.