先定义一个实体类

@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. PHP时间戳和日期转换

    获取当前时间 <?php var_dump(time()); //获取当前时间戳 int(1502245603) 时间戳转换为时间,可以用date(‘Y-m-s h:i:s’, 具体时间戳来实现 ...

  2. 方法调用---springMVC中调用controller的方法

    我们有一个路由StudentController,里面有一个方法count().如果要在另外一个GradeController中调用count()方法有2种方式: 因为StudentControlle ...

  3. API的防重

    说说API的防重放机制 2017-03-20 18:19 by 轩脉刃, 685 阅读, 7 评论, 收藏, 编辑 说说API的防重放机制 我们在设计接口的时候,最怕一个接口被用户截取用于重放攻击.重 ...

  4. 【LOJ】#2122. 「HEOI2015」小 Z 的房间

    题解 又是一道取模不给质数的毒瘤矩阵树题 不会写分数类--然后发现了网上过于神仙的题解类似与辗转相除的这样把某一个位置消成0 orz 代码 #include <bits/stdc++.h> ...

  5. P1006 传纸条 多维DP

    题目描述 小渊和小轩是好朋友也是同班同学,他们在一起总有谈不完的话题.一次素质拓展活动中,班上同学安排做成一个mm行nn列的矩阵,而小渊和小轩被安排在矩阵对角线的两端,因此,他们就无法直接交谈了.幸运 ...

  6. 使用Golang开发一个本地代理

    引言 最近需要对接一个接口,人家提供了两种调用方式,第一种是基于IE浏览器的Active,第二种是动态链接库dll.我们公司的产品不支持IE,所以只能通过调用dll来完成了. 之前我已经用Java实现 ...

  7. SpringBoot详细研究-01基础

    Springboot可以说是当前最火的java框架了,非常适合于"微服务"思路的开发,大幅缩短软件开发周期. 概念 过去Spring充满了配置bean的xml文件,随着spring ...

  8. 基于图文界面的蓝牙扫描工具btscanner

    基于图文界面的蓝牙扫描工具btscanner   btscanner是Kali Linux内置的一款蓝牙扫描工具.它提供图文界面,更便于渗透测试人员查看扫描信息.该工具会自动使用主机所有的蓝牙接口,并 ...

  9. 缩减apk大小

    韩梦飞沙  韩亚飞  313134555@qq.com  yue31313  han_meng_fei_sha 1,重复的资源,不用的资源,删去. 2,使用混淆,可以优化. 3,尽量的使用代码,或者其 ...

  10. RelativeSource的用法

    绑定自身的数据 <Style TargetType="Button"> <Setter Property="Width" Value=&quo ...