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:5 | ISBN:9780136091813 | Edition: 2

Question

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.

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.