Write a method called sortAndRemoveDuplicates that accepts a list of integers as its parameter and rearranges the list’s elements into sorted ascending order, as well as removing all duplicate values from the list. For example, the list (7, 4, –9, 4, 15, 8, 27, 7, 11, –5, 32, –9, –9) would become (–9, –5, 4, 7, 8, 11, 15, 27, 32) after a call to your method. Use a Set as part of your solution.
package collections;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class SortAndRemove {
public List<Integer> sortAndRemoveDuplicates(List<Integer> list) {
// we are using LinkedHashSet to remove duplicates and maintain insertion order
Set<Integer> distinctElements = new LinkedHashSet<Integer>(list);
// using List to call the individual elements using loop in main method
// this method return the List type collection
List<Integer> sortedList = new ArrayList<Integer>(distinctElements);
// using java streams in java 8
sortedList = sortedList.stream().sorted().collect(Collectors.toList());
return sortedList;
}
public static void main(String[] args) {
SortAndRemove sandr = new SortAndRemove();
// creating list and adding the random elements to the list
List<Integer> list1 = new ArrayList<Integer>();
Collections.addAll(list1, 7, 4, -9, 4, 15, 8, 27, 7, 11, -5, 32, -9, -9);
// below list contains unique and sorted elements
list1 = sandr.sortAndRemoveDuplicates(list1);
System.out.print("The sorted list without duplicate elements: \n");
for (int i = 0; i < list1.size(); i++) {
System.out.print(list1.get(i) + ", ");
}
}
}
Output:
The sorted list without duplicate elements:
-9, -5, 4, 7, 8, 11, 15, 27, 32,