SHARE
SPREAD
HELP

The Tradition of Sharing

Help your friends and juniors by posting answers to the questions that you know. Also post questions that are not available.


To start with, Sr2Jr’s first step is to reduce the expenses related to education. To achieve this goal Sr2Jr organized the textbook’s question and answers. Sr2Jr is community based and need your support to fill the question and answers. The question and answers posted will be available free of cost to all.

 

#
Authors:
Stuart Reges, Marty Stepp
Chapter:
Java Collections Framework
Exercise:
Exercises
Question:1 | ISBN:9780136091813 | Edition: 2

Question

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?)

TextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbookTextbook

Answer

// 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, 

 

0 0

Discussions

Post the discussion to improve the above solution.