PlsWork
PlsWork

Reputation: 2158

How to sort int[] with multi-line lambda expression in Java

This question has an answer for how to sort a List with a multi-line lambda expression:

list.sort((o1, o2) -> {
    int cmp = o1.getGroup().compareTo(o2.getGroup());
    if (cmp == 0)
        cmp = Integer.compare(o1.getAge(), o2.getAge());
    if (cmp == 0)
        cmp = o1.getName().compareTo(o2.getName());
    return cmp;

});

Unfortunately, this does not seem to work for a raw array int[] arr:

Arrays.sort(arr, (int1, int2) -> {
    // some lambda, various if-else statements for example
});

How to use a multi-line lambda expression in Arrays.sort() to sort a raw array?

I'm fine with any other approach (does not have to use Arrays.) as long as it uses lambda expressions (no comparators).

Upvotes: 0

Views: 503

Answers (1)

WJS
WJS

Reputation: 40034

If you're intent on doing it using only lambdas then this will work with both lists and arrays. This presume your group and age fields are ints.

        Comparator<Item> comp = (o1, o2) -> {
            int cmp = Integer.compare(o1.getGroup(), o2.getGroup());
            cmp = cmp == 0 ? Integer.compare(o1.getAge(), o2.getAge()) : cmp;
            cmp = cmp == 0 ? o1.getName().compareTo(o2.getName()) : cmp;
            return cmp;
        };

        list.sort(comp);

        Arrays.sort(items, comp);

But I would use a List and do it as follows:

    list.sort(Comparator.comparing(Item::getGroup)
                .thenComparing(Item::getAge)
                .thenComparing(Item::getName));

And even your lambda expression is a comparator. You can't compare without some sort of Comparator no matter how you construct it.

Upvotes: 1

Related Questions