使用lambda进行简化处理详见
Java8使用lambda表达式代替匿名类进行排序
对象示例 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;
}
}
流操作排序
先按年龄倒序 ,其中年龄相同的,再按头发量正序 排序
new一个匿名的Comparator,重写其compare方法。
其中
年龄是降序,所以 当o1.getAge() > o2.getAge() 返回 -1;
头发量是正序,且字段是BigInteger类型,直接使用其compareTo方法即可
public static void test7(List<User> userList) {
List<User> userListSorted = userList.stream()
.sorted(new Comparator<User>() {
@Override
public int compare(User o1, User o2) {
if (o1.getAge() > o2.getAge()) {
return -1;
} else if (o1.getAge() == o2.getAge()) {
// o1.getHairCount()>o2.getHairCount() 时,compareTO返回1
return o1.getHairCount().compareTo(o2.getHairCount());
} else {
return 1;
}
}
})
.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);
test7(userList);
}
运行结果
张三毛20 - 11111
张三20 - 22222
李四19 - 33333
张三10 - 11111