对象示例 User
package will.tools;
import java.math.BigInteger;
public class User {
private String name;
private String sex;
private int age;
private BigInteger hairCount;
public BigInteger getHairCount() {
return hairCount;
}
public void setHairCount(BigInteger hairCount) {
this.hairCount = hairCount;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
流操作排序
先按年龄倒序(reversed),其中年龄相同的,再按头发量正序 排序
public static void test5(List<User> userList) {
List<User> userListSorted = userList.parallelStream()
.sorted(Comparator.comparing(User::getHairCount))
.sorted(Comparator.comparing(User::getAge).reversed())
.collect(Collectors.toList());
userListSorted.forEach(n -> System.out.println(n.getName() + n.getAge()+" - "+n.getHairCount()));
}
还可以使用 thenComparing()方法,以上代码等同于
public static void test6(List<User> userList) {
List<User> userListSorted = userList.parallelStream()
.sorted(Comparator.comparing(User::getAge).reversed()
.thenComparing(User::getHairCount))
.collect(Collectors.toList());
userListSorted.forEach(n -> System.out.println(n.getName() + n.getAge()+" - "+n.getHairCount()));
}
调用验证示例
public static void main(String[] args) {
User u1 = new User();
u1.setAge(10);
u1.setName("张三");
u1.setSex("男");
u1.setHairCount(new BigInteger("11111"));
User u2 = new User();
u2.setAge(20);
u2.setName("张三");
u2.setSex("男");
u2.setHairCount(new BigInteger("22222"));
User u3 = new User();
u3.setAge(19);
u3.setName("李四");
u3.setSex("男");
u3.setHairCount(new BigInteger("33333"));
User u4 = new User();
u4.setAge(20);
u4.setName("张三毛");
u4.setSex("男");
u4.setHairCount(new BigInteger("11111"));
List<User> userList = new ArrayList<>();
userList.add(u1);
userList.add(u2);
userList.add(u3);
userList.add(u4);
//test1(userList);
//test2(userList);
test5(userList);
}
运行结果
张三毛20 - 11111
张三20 - 22222
李四19 - 33333
张三10 - 11111