Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

java - Sorting multiple attribute with Lambda Expressions

This is my list:

Name: Ben     || Age: 5 || Group: 1
Name: Andy    || Age: 6 || Group: 2
Name: Charlie || Age: 6 || Group: 2
Name: Ben     || Age: 5 || Group: 1
Name: Andy    || Age: 5 || Group: 2
Name: Charlie || Age: 5 || Group: 1

I want to sort the list by Group, if Group is equal then by Age, and if Age is equal then by Name. But so far I can only sort by one attribute, using Lambda Expressions:

list.sort((Object o1, Object o2) -> o1.getGroup().compareTo(o2.getGroup()));

If I try

o1.getGroup().compareTo(o2.getGroup()) && o1.getAge().compareTo(o2.getAge())

it's turned out error...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change lambda expression to lambda {block}, and you don't have to specify the parameter types:

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;
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...