Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream sort by 2 fields

I have list of items that i need to sort by 2 parameters, first param is orderIndex, and i have that part working correctly (see bellow code), second param after orderIndex is amount. So basically first items should be ones with lowest order index, and they needs to be sorted by amount.

result.stream().sorted { s1, s2 -> s1.intervalType.orderIndex.compareTo(s2.intervalType.orderIndex) }.collect(Collectors.toList())

At this moment i have that code, and it is sorting just by orderIndex, second parameter amount is located at s1.item.amount.

Any idea how to upgrade this code with second ordering param ?

I have found this example

persons.stream().sorted(Comparator.comparing(Person::getName).thenComparing(Person::getAge));

my question here is, how to access other object in Person, for example in my case i have IntervalType object in object that i'm sorting, and i need to use intervalType.orderIndex

Note:

Just for note i need this in Kotlin not in Java.

like image 222
Sahbaz Avatar asked May 30 '18 16:05

Sahbaz


People also ask

How do I sort a list by multiple fields?

To sort on multiple fields, we must first create simple comparators for each field on which we want to sort the stream items. Then we chain these Comparator instances in the desired order to give GROUP BY effect on complete sorting behavior.

How do you compare two fields in Java?

reflect. Field is used to compare two field objects. This method compares two field objects and returns true if both objects are equal otherwise false. The two Field objects are considered equal if and only if when they were declared by the same class and have the same name and type.

Can you sort a stream Java?

We can sort the stream using natural ordering, as well as ordering provided by a Comparator. For this, we have two overloaded variants of the sorted() API: sorted() – sorts the elements of a Stream using natural ordering; the element class must implement the Comparable interface.


1 Answers

You can use Comparator for sorting data using streams

//first comparison
Comparator<YourType> comparator = Comparator.comparing(s -> s.intervalType.orderIndex);

//second comparison
comparator = comparator.thenComparing(Comparator.comparing(s-> s.item.amount));

//sorting using stream
result.stream().sorted(comparator).collect(Collectors.toList())
like image 121
toltman Avatar answered Sep 18 '22 22:09

toltman