Reputation: 1272
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.
Upvotes: 8
Views: 12430
Reputation: 487
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())
Upvotes: 18
Reputation: 3453
If you are doing it with Kotlin - you should do it in Kotlin way.
heaving Internal
class
class Internal(val orderIndex: Int, val ammount: Int)
You can easily write a any combination of comparators with compareBy
// result: List<Internal>
result.sortedWith(compareBy( {it.orderIndex}, {it.ammount} ))
In your task there is no need in streams, you can do it direclty.
In case you need exactly streams - use this compareBy
aggregate inside stream:
result.stream().sorted(compareBy( ... ).collect( ... )
Upvotes: 0
Reputation: 1272
I have found best possible way to do it, since i'm using Kotlin it can be done like this:
result.sortedWith(compareBy({ it.intervalType.orderIndex }, { it.item.amount }))
Upvotes: 2