Modify the Sieve program developed in Section 11.1 to make two optimizations. First, instead of storing all integers up to the maximum in the numbers list, store only 2 and all odd numbers from 3 upward. Second, write code to ensure that if the first number in the numbers list ever reaches the square root of the maximum, all remaining values from the numbers list are moved into the primes list. (Why is this a valid operation?)
// 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,