how to sort a iterable in java

https:/‮.www/‬lautturi.com
how to sort a iterable in java

To sort an Iterable in Java, you can use the sorted method of the Stream interface and pass it a comparator that defines the sort order.

Here's an example of how you can do this:

Iterable<String> iterable = Arrays.asList("apple", "banana", "cherry");

List<String> sortedList = StreamSupport.stream(iterable.spliterator(), false)
    .sorted(Comparator.naturalOrder())
    .collect(Collectors.toList());

System.out.println(sortedList);

This code will convert the Iterable to a stream, sort the elements in natural order (ascending order for strings), and collect the sorted elements into a List. The output will be:

[apple, banana, cherry]

You can customize the comparator to sort the elements based on different criteria, such as the length of the strings or the reverse order. For example, to sort the elements in descending order, you can use the reverseOrder method of the Comparator class:

Iterable<String> iterable = Arrays.asList("apple", "banana", "cherry");

List<String> sortedList = StreamSupport.stream(iterable.spliterator(), false)
    .sorted(Comparator.reverseOrder())
    .collect(Collectors.toList());

System.out.println(sortedList);

This code will sort the elements in reverse order, and the output will be:

[cherry, banana, apple]

Note that the sorted method only works on sequential streams, so if the Iterable represents a parallel stream, you will need to use the sequential method to convert it to a sequential stream before sorting.

Created Time:2017-11-01 20:43:01  Author:lautturi