直接上代码:
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;/*** List 对象属性排序*/@Data
@AllArgsConstructor
class Commodity
{private String name;private Double price;private Integer count;
}public class Test {public static void main(String[] args) {// 创建参数List<Commodity> list = Lists.newArrayList(new Commodity("1", 3.3, 10),new Commodity("2", null, 30),new Commodity("3", 4.4, 20),new Commodity("4", 6.6, null),new Commodity("5", 8.8, 20),new Commodity("6", 8.8, 20),new Commodity("7", 7.7, 60),new Commodity("8", 7.7, 60));// 多排序条件List<Commodity> orderShopList = list.stream().sorted(Comparator// 先按数量降序(由于是降序,nullsFirst()方法会将null值放在后面).comparing(Commodity::getCount, Comparator.nullsFirst(Integer::compareTo).reversed())// 然后按价格升序(由于是升序,nullsFirst()方法会将null值放在前面).thenComparing(Commodity::getPrice, Comparator.nullsFirst(Double::compareTo))// 然后按名称降序(如果不设置null值排序规则,字段为null会报错).thenComparing(Commodity::getName, Comparator.reverseOrder())).collect(Collectors.toList());// 打印排序结果orderShopList.forEach(System.out::println);}
}
运行结果如下: