0

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).

3
  • 2
    Does this answer your question? java comparator for arrays sort Commented Apr 7, 2020 at 16:05
  • 2
    Not very efficient, but arr = Arrays.stream(arr).boxed().sorted((int1, int2) -> { /* your logic */ }).mapToInt(Integer::intValue).toArray(); would work. Commented Apr 7, 2020 at 16:10
  • @user85421 Thank you. Commented Apr 7, 2020 at 16:43

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.