本文主要是介绍Java 集合按照多字段排序,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
以 Apple 实体为例,先按 name 升序排序,再按 size 降序排序
测试代码
Apple 类
package com.me.entity;import lombok.Builder;
import lombok.Data;/*** @author yanyg* @since 2020/8/5*/
@Data
@Builder
public class Apple {private String color;private String name;private Integer size;}
AppleComparatorTest 类
package cn.me.mybatis;import cn.yto.utils.JsonUtil;
import com.me.entity.Apple;
import org.assertj.core.util.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;import java.util.Comparator;
import java.util.List;/*** @author yanyg* @since 2020/8/5*/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringBootTest.class)
public class AppleComparatorTest {@Testpublic void comparatorApples() {List<Apple> apples = buildApples();Comparator<Apple> byName = Comparator.comparing(Apple::getName);Comparator<Apple> bySizeDesc = Comparator.comparing(Apple::getSize).reversed();/*** 先按 name 升序排序,再按 size 降序排序, 但是 name 和 size 都不能为 null*/apples.sort(byName.thenComparing(bySizeDesc));apples.stream().forEach(t -> System.out.println(JsonUtil.toJson(t)));}@Testpublic void comparatorApplesTwo() {List<Apple> apples = buildApples();// name 为 null 时,排在最后面Comparator<Apple> byName = Comparator.comparing(apple -> apple.getName(), Comparator.nullsLast(String::compareTo));// size 为 null 时,排在最后面Comparator<Apple> bySizeDesc = Comparator.comparing(apple -> apple.getSize(),Comparator.nullsFirst(Integer::compareTo).reversed());/*** 先按 name 升序排序,再按 size 降序排序, name 和 size 可为 null*/apples.sort(byName.thenComparing(bySizeDesc));// since 1.8//apples = apples.stream().sorted(byName.thenComparing(bySizeDesc)).collect(Collectors.toList());apples.stream().forEach(t -> System.out.println(JsonUtil.toJson(t)));}public List<Apple> buildApples() {List<Apple> apples = Lists.newArrayList();apples.add(Apple.builder().name("red apple").size(180).build());apples.add(Apple.builder().name("red apple").size(150).build());// size 为 nullapples.add(Apple.builder().name("red apple").build());apples.add(Apple.builder().name("big apple").size(260).build());apples.add(Apple.builder().name("small apple").size(150).build());apples.add(Apple.builder().name("big apple").size(300).build());apples.add(Apple.builder().name("green apple").size(310).build());// name 为 nullapples.add(Apple.builder().size(260).build());return apples;}}
参考文档
- java list 按照多字段排序
这篇关于Java 集合按照多字段排序的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!