Set sort order in java

Java 8 – How to sort Set with stream.sorted()

In this quick tutorial, we’ll learn how to sort Set in Java 8. stream.sorted() is a predefined method of Stream interface for sorting a Set or any Collection implemented classes.

Sorting the elements of Set is similar to the sorting of the list.

1. Natural/Default Sorting Order

In this, we have a Set of employees and the type of the set is String.

package org.websparrow.sorting; import java.util.Comparator; import java.util.HashSet; import java.util.Set; public class SetSorting < public static void main(String[] args) < Setemployees = new HashSet<>(); employees.add("Sunny Tiwari"); employees.add("Ashutosh Pandey"); employees.add("Vipin Singh"); employees.add("Mintoo Prasad"); System.out.println("--- Set before sorted ---"); employees.forEach(System.out::println); System.out.println("--- Set after sorted ---"); employees.stream().sorted().forEach(System.out::println); > >
--- Set before sorted --- Vipin Singh Ashutosh Pandey Mintoo Prasad Sunny Tiwari --- Set after sorted --- Ashutosh Pandey Mintoo Prasad Sunny Tiwari Vipin Singh

Alternately, we can also pass the Comparator.naturalOrder() as argument in overloaded sorted() method i.e. sorted(Comparator.naturalOrder()) which gives the same output.

employees .stream() .sorted(Comparator.naturalOrder()) .forEach(System.out::println);

Similarly, we can also compare the elements one by one by calling compareTo(String object) method as we do in the older version of Java. And it also produces the same output.

employees .stream() .sorted((o1, o2) -> o1.compareTo(o2)) .forEach(System.out::println);

2. Sorting in Reverse Order

The Set elements can be sorted in revered order by passing the Comparator.naturalOrder() . It returns a comparator that imposes the reverse of the natural ordering.

package org.websparrow.sorting; import java.util.Comparator; import java.util.HashSet; import java.util.Set; public class SetSortingReverseOrder < public static void main(String[] args) < Setset = new HashSet<>(); set.add("Sunny Tiwari"); set.add("Ashutosh Pandey"); set.add("Vipin Singh"); set.add("Mintoo Prasad"); System.out.println("--- Set before sorted ---"); set.forEach(System.out::println); System.out.println("--- Set after sorted (Reverse order) ---"); set.stream().sorted(Comparator.reverseOrder()) .forEach(System.out::println); System.out.println("--- Set after sorted (Reverse order) Old days ---"); set.stream().sorted((o1, o2) -> o2.compareTo(o1)) .forEach(System.out::println); > >
--- Set before sorted --- Vipin Singh Ashutosh Pandey Mintoo Prasad Sunny Tiwari --- Set after sorted (Reverse order) --- Vipin Singh Sunny Tiwari Mintoo Prasad Ashutosh Pandey --- Set after sorted (Reverse order) Old days --- Vipin Singh Sunny Tiwari Mintoo Prasad Ashutosh Pandey

3. Sorting Set of Custom Object

We can also sort custom object Set by using stream.sorted() method. Let’s we have Car class along with its attributes like id, brand name, model year, etc.

package org.websparrow.sorting; public class Car < // Generate Getters and Setters. private int id; private String brand; private int modelYear; public Car(int id, String brand, int modelYear) < this.id = id; this.brand = brand; this.modelYear = modelYear; >@Override public String toString() < return "Car [id=" + id + ", brand=" + brand + ", modelYear=" + modelYear + "]"; >>

3.1 Sort by id (Natural/Default Sort Order)

package org.websparrow.sorting; import java.util.Comparator; import java.util.HashSet; import java.util.Set; public class SetSortingCustomObject < public static void main(String[] args) < Setset = new HashSet<>(); set.add(new Car(166, "Tata", 1967)); set.add(new Car(112, "Mahindra", 1978)); set.add(new Car(66, "Hindustan Motors", 1950)); set.add(new Car(203, "BMW", 1998)); System.out.println("--- Cars before sorted ---"); set.forEach(System.out::println); System.out.println("--- Cars after sorted ---"); set.stream().sorted(Comparator.comparingInt(Car::getId)) .forEach(System.out::println); System.out.println("--- Cars after sorted (Old days) ---"); set.stream().sorted((o1, o2) -> o1.getId() - o2.getId()) .forEach(System.out::println); > >
--- Cars before sorted --- Car [id=166, brand=Tata, modelYear=1967] Car [id=112, brand=Mahindra, modelYear=1978] Car [id=66, brand=Hindustan Motors, modelYear=1950] Car [id=203, brand=BMW, modelYear=1998] --- Cars after sorted --- Car [id=66, brand=Hindustan Motors, modelYear=1950] Car [id=112, brand=Mahindra, modelYear=1978] Car [id=166, brand=Tata, modelYear=1967] Car [id=203, brand=BMW, modelYear=1998] --- Cars after sorted (Old days) --- Car [id=66, brand=Hindustan Motors, modelYear=1950] Car [id=112, brand=Mahindra, modelYear=1978] Car [id=166, brand=Tata, modelYear=1967] Car [id=203, brand=BMW, modelYear=1998]

3.2 Sort by id (Reverse Order)

Comparator ‘s reversed() method is used to reveres the elements of a sorted Set.

package org.websparrow.sorting; import java.util.Comparator; import java.util.HashSet; import java.util.Set; public class SetSortingCustomObject < public static void main(String[] args) < Setset = new HashSet<>(); set.add(new Car(166, "Tata", 1967)); set.add(new Car(112, "Mahindra", 1978)); set.add(new Car(66, "Hindustan Motors", 1950)); set.add(new Car(203, "BMW", 1998)); System.out.println("--- Cars before sorted ---"); set.forEach(System.out::println); System.out.println("--- Cars after sorted (Reverse order)---"); set.stream().sorted(Comparator.comparingInt(Car::getId).reversed()) .forEach(System.out::println); System.out.println("--- Cars after sorted (Reverse order) Old days ---"); set.stream().sorted((o1, o2) -> o2.getId() - o1.getId()) .forEach(System.out::println); > >
--- Cars before sorted --- Car [id=166, brand=Tata, modelYear=1967] Car [id=112, brand=Mahindra, modelYear=1978] Car [id=66, brand=Hindustan Motors, modelYear=1950] Car [id=203, brand=BMW, modelYear=1998] --- Cars after sorted (Reverse order)--- Car [id=203, brand=BMW, modelYear=1998] Car [id=166, brand=Tata, modelYear=1967] Car [id=112, brand=Mahindra, modelYear=1978] Car [id=66, brand=Hindustan Motors, modelYear=1950] --- Cars after sorted (Reverse order) Old days --- Car [id=203, brand=BMW, modelYear=1998] Car [id=166, brand=Tata, modelYear=1967] Car [id=112, brand=Mahindra, modelYear=1978] Car [id=66, brand=Hindustan Motors, modelYear=1950]

3.3 Sort by brand

Similarly, we can also sort Car by its brand name.

System.out.println("--- Cars after sorted ---"); set.stream().sorted(Comparator.comparing(Car::getBrand)) .forEach(System.out::println); System.out.println("--- Cars after sorted Old days ---"); set.stream().sorted((o1, o2) -> o1.getBrand().compareTo(o2.getBrand())) .forEach(System.out::println);

3.4 Sort by brand (Reverse Order)

System.out.println("--- Cars after sorted (Reverse order)---"); set.stream().sorted(Comparator.comparing(Car::getBrand).reversed()) .forEach(System.out::println); System.out.println("--- Cars after sorted (Reverse order) Old days ---"); set.stream().sorted((o1, o2) -> o2.getBrand().compareTo(o1.getBrand())) .forEach(System.out::println);

References

Источник

Interface SortedSet

Type Parameters: E — the type of elements maintained by this set All Superinterfaces: Collection , Iterable , Set All Known Subinterfaces: NavigableSet All Known Implementing Classes: ConcurrentSkipListSet , TreeSet

A Set that further provides a total ordering on its elements. The elements are ordered using their natural ordering, or by a Comparator typically provided at sorted set creation time. The set’s iterator will traverse the set in ascending element order. Several additional operations are provided to take advantage of the ordering. (This interface is the set analogue of SortedMap .)

All elements inserted into a sorted set must implement the Comparable interface (or be accepted by the specified comparator). Furthermore, all such elements must be mutually comparable: e1.compareTo(e2) (or comparator.compare(e1, e2) ) must not throw a ClassCastException for any elements e1 and e2 in the sorted set. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException .

Note that the ordering maintained by a sorted set (whether or not an explicit comparator is provided) must be consistent with equals if the sorted set is to correctly implement the Set interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Set interface is defined in terms of the equals operation, but a sorted set performs all element comparisons using its compareTo (or compare ) method, so two elements that are deemed equal by this method are, from the standpoint of the sorted set, equal. The behavior of a sorted set is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Set interface.

All general-purpose sorted set implementation classes should provide four «standard» constructors: 1) A void (no arguments) constructor, which creates an empty sorted set sorted according to the natural ordering of its elements. 2) A constructor with a single argument of type Comparator , which creates an empty sorted set sorted according to the specified comparator. 3) A constructor with a single argument of type Collection , which creates a new sorted set with the same elements as its argument, sorted according to the natural ordering of the elements. 4) A constructor with a single argument of type SortedSet , which creates a new sorted set with the same elements and the same ordering as the input sorted set. There is no way to enforce this recommendation, as interfaces cannot contain constructors.

Note: several methods return subsets with restricted ranges. Such ranges are half-open, that is, they include their low endpoint but not their high endpoint (where applicable). If you need a closed range (which includes both endpoints), and the element type allows for calculation of the successor of a given value, merely request the subrange from lowEndpoint to successor(highEndpoint) . For example, suppose that s is a sorted set of strings. The following idiom obtains a view containing all of the strings in s from low to high , inclusive:

SortedSet sub = s.subSet(low, high+"\0");

A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the Strings in s from low to high , exclusive:

SortedSet sub = s.subSet(low+"\0", high);

This interface is a member of the Java Collections Framework.

Источник

Читайте также:  Winerror 10013 python socket
Оцените статью