先定义一个实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Human { private String name;
private int age; }

下面的操作都基于这个类来进行操作。这里面使用了Lombok类库,它用注解的方式实现了基本的get和set等方法,让代码看起来更加的优雅。

JAVA8之前的List排序操作

在Java8之前,对集合排序只能创建一个匿名内部类

new Comparator<Human>() {
@Override
public int compare(Human h1, Human h2) {
return h1.getName().compareTo(h2.getName());
}
}

下面是简单的对Humans进行排序(按名称正序)

@Test
public void testSortByName_with_plain_java() throws Exception { ArrayList<Human> humans = Lists.newArrayList(
new Human("tomy", 22),
new Human("li", 25)
); Collections.sort(humans, new Comparator<Human>() { public int compare(Human h1, Human h2) {
return h1.getName().compareTo(h2.getName());
}
}); Assert.assertThat(humans.get(0), equalTo(new Human("li", 25)));
}

使用Lambda的List排序

使用JAVA8函数式方式的比较器

(Human h1, Human h2) -> h1.getName().compareTo(h2.getName())

下面是使用JAVA8函数式的比较的例子

@Test
public void testSortByName_with_lambda() throws Exception { ArrayList<Human> humans = Lists.newArrayList(
new Human("tomy", 22),
new Human("li", 25)
);
humans.sort((Human h1, Human h2) -> h1.getName().compareTo(h2.getName())); Assert.assertThat("tomy", equalTo(humans.get(1).getName())); }

没有类型定义的排序

对于上面的表达式还可以进行简化,JAVA编译器可以根据上下文推测出排序的类型:

(h1, h2) -> h1.getName().compareTo(h2.getName())

简化后的比较器是这样的:

@Test
public void testSortByNameSimplify_with_lambda() throws Exception { ArrayList<Human> humans = Lists.newArrayList(
new Human("tomy", 22),
new Human("li", 25)
);
humans.sort((h1, h2) -> h1.getName().compareTo(h2.getName())); Assert.assertThat("tomy", equalTo(humans.get(1).getName())); }

使用静态方法引用

JAVA8还可以提供使用Lambda表达式的静态类型引用,我们在Human类增加一个静态比较方法,如下:

public static int compareByNameThenAge(Human h1, Human h2) {

   if (h1.getName().equals(h2.getName())) {
return Integer.compare(h1.getAge(), h2.getAge());
}
return h1.getName().compareTo(h2.getName());
}

然后就可以在humans.sort使用这个引用

@Test
public void testSort_with_givenMethodDefinition() throws Exception { ArrayList<Human> humans = Lists.newArrayList(
new Human("tomy", 22),
new Human("li", 25)
);
humans.sort(Human::compareByNameThenAge);
Assert.assertThat("tomy", is(equalTo(humans.get(1).getName())));
}

使用单独的Comparator

JAVA8已经提供了很多方便的比较器供我们使用,比如Comparator.comparing方法,所以可以使用Comparator.comparing方法来实现根据Human的name进行比较的操作:

@Test
public void testSort_with_givenInstanceMethod() throws Exception { ArrayList<Human> humans = Lists.newArrayList(
new Human("tomy", 22),
new Human("li", 25)
); Collections.sort(humans, Comparator.comparing(Human::getName));
Assert.assertThat("tomy", equalTo(humans.get(1).getName()));
}

反序

JDK8中也提供了一个支持倒序排序的方法方便我们更快的进行倒序

@Test
public void testSort_with_comparatorReverse() throws Exception { ArrayList<Human> humans = Lists.newArrayList(
new Human("tomy", 22),
new Human("li", 25)
); Comparator<Human> comparator = (h1, h2) -> h1.getName().compareTo(h2.getName());
humans.sort(comparator.reversed());
Assert.assertThat("tomy", equalTo(humans.get(0).getName())); }

使用多个条件进行排序

Lambda提供了更复杂的表达式,还可以先对name排序再根据age进行排序:

@Test
public void testSort_with_multipleComparator() throws Exception { ArrayList<Human> humans = Lists.newArrayList(
new Human("tomy", 22),
new Human("li", 25)
); Comparator<Human> comparator = (h1, h2) -> { if (h1.getName().equals(h2.getName())) {
return Integer.compare(h1.getAge(), h2.getAge());
}
return h1.getName().compareTo(h2.getName());
};
humans.sort(comparator.reversed());
Assert.assertThat("tomy", equalTo(humans.get(0).getName())); }

使用多个条件进行排序-组合的方式

Comparator对这种组合的排序有更优雅实现,从JDK8开始,我们可以使用链式操作进行复合操作来构建更复杂的逻辑:

@Test
public void testSort_with_multipleComparator_composition() throws Exception { ArrayList<Human> humans = Lists.newArrayList(
new Human("tomy", 22),
new Human("tomy", 25)
); humans.sort(Comparator.comparing(Human::getName).thenComparing(Human::getAge));
Assert.assertThat(humans.get(0), equalTo(new Human("tomy", 22))); }

JAVA8 List排序的更多相关文章

  1. Java 8 对 List<List<String>> 排序

    Java 8 对 List<List> 排序 import java.util.ArrayList; import java.util.List; import java.util.str ...

  2. Java8函数之旅 (五) -- Java8中的排序

    前言    对数据进行排序是平常经常会用到的操作之一,使用Jav8排序可以减少你在排序这方面的代码量,优化你的代码. 测试用例代码 定义个实体类User,拥有姓名name,年龄age,积分credit ...

  3. Java中list<Object[]>、list<Student>、list<Map<String,String>>排序

    1:list<Object[]>的排序   public static void main(String[] args) { // TODO Auto-generated method s ...

  4. Java8之集合排序

    1,List<Map<String,Object>>格式 //排序 Comparator<Map<String, Object>> comparator ...

  5. HDU 6096 String 排序 + 线段树 + 扫描线

    String Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others) Problem De ...

  6. 【JAVA8】Set排序四种写法

    工作中遇到,写了很久以前的写法,师兄给了很多建议,于是整理了一下.孔子曰:"你知道茴香豆的茴字有几种写法吗?" 第一种,平常的写法: public class App { publ ...

  7. 【java基础学习一】int[]、Integer[]、String[] 排序( 正序、倒叙)、去重

    调用: //重复项有9.5.1.2 int[] ints = new int[]{9,4,7,8,2,5,1,6,2,5,9,1}; arrayIntTest(ints); ///////////// ...

  8. Dictionary<string, string> 排序

    .net framework 2.0 版 Dictionary<string, string> collection = new Dictionary<string, string& ...

  9. Java8中String.join方法

    List names=new ArrayList<String>(); names.add("1"); names.add("2"); names. ...

  10. Java8 map value排序

    /** * Map value降序排序 * @param map * @param <K> * @param <V> * @return LinkedHashMap */ pu ...

随机推荐

  1. .NetCore生产环境下构建Consul(单个DC数据中心)的服务器健康检查

    下载最新的consul程序 consul 启动方式有两种 server 和client 默认是client 如果你不需要记录数据可以用 consul agent -dev 来启动 consul age ...

  2. nginx用户认证配置( Basic HTTP authentication)及认证原理和实现

    https://blog.csdn.net/guyue35/article/details/53906843

  3. IScroll5安卓重复点击兼容问题处理

    最近在做移动web开发,使用IScroll 5 的时候出现了设备之间兼容的问题: 情景如下: Android手机:点击滚动区间内的选项时出现点击时间重叠(类似事件冒泡的行为)问题 Apple手机:木有 ...

  4. Linux 安装操作系统标准

    一.注意事项. 1.虚拟机安装不做过多介绍. 2.若为主机(非服务器)安装需要按照如下步骤: a.首先需要将u盘刻录pe系统然后设置开机引导为u盘启动后进入,将以前的硬盘分区全部删除. b.若主机bi ...

  5. 【IObit】五大软件激活码( Advanced Systemcare....)

    IObit Malware Fighter 6Pro 破解: 打开软件安装位置,下载替换dll文件 链接: https://pan.baidu.com/s/1Euz87MCANuCnRqZsMQ_w4 ...

  6. C向C++改造

    步骤: 1. 把c文件后缀名换成cpp2. Android.mk文件中的hello.c也要换成hello.cpp3. c++的使用的环境变量结构体中,访问了c使用的结构体的函数指针,函数名全部都是一样 ...

  7. P2398 GCD SUM

    P2398 GCD SUM一开始是憨打表,后来发现打多了,超过代码长度了.缩小之后是30分,和暴力一样.正解是,用f[k]表示gcd为k的一共有多少对.ans=sigma k(1->n) k*f ...

  8. UICollectionView 常用操作

    1 iOS开发 - UICollectionView点击展开收起

  9. DBUtils工具

    DBUtils工具 简介 是Apache旗下的产品.是对jdbc的简单封装.提供出通用的jdbc操作方法.简化开发者使用jdbc的成本. 常用的API说明 |- QueryRunner类: 主要进行j ...

  10. Codeforces Round #272 (Div. 2) E. Dreamoon and Strings 动态规划

    E. Dreamoon and Strings 题目连接: http://www.codeforces.com/contest/476/problem/E Description Dreamoon h ...