JAVA8 List排序
先定义一个实体类
@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排序的更多相关文章
- Java 8 对 List<List<String>> 排序
Java 8 对 List<List> 排序 import java.util.ArrayList; import java.util.List; import java.util.str ...
- Java8函数之旅 (五) -- Java8中的排序
前言 对数据进行排序是平常经常会用到的操作之一,使用Jav8排序可以减少你在排序这方面的代码量,优化你的代码. 测试用例代码 定义个实体类User,拥有姓名name,年龄age,积分credit ...
- Java中list<Object[]>、list<Student>、list<Map<String,String>>排序
1:list<Object[]>的排序 public static void main(String[] args) { // TODO Auto-generated method s ...
- Java8之集合排序
1,List<Map<String,Object>>格式 //排序 Comparator<Map<String, Object>> comparator ...
- HDU 6096 String 排序 + 线段树 + 扫描线
String Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others) Problem De ...
- 【JAVA8】Set排序四种写法
工作中遇到,写了很久以前的写法,师兄给了很多建议,于是整理了一下.孔子曰:"你知道茴香豆的茴字有几种写法吗?" 第一种,平常的写法: public class App { publ ...
- 【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); ///////////// ...
- Dictionary<string, string> 排序
.net framework 2.0 版 Dictionary<string, string> collection = new Dictionary<string, string& ...
- Java8中String.join方法
List names=new ArrayList<String>(); names.add("1"); names.add("2"); names. ...
- Java8 map value排序
/** * Map value降序排序 * @param map * @param <K> * @param <V> * @return LinkedHashMap */ pu ...
随机推荐
- <转> 解决异常:IllegalStateException: Fragment <ThisFragment> is not currently in the FragmentManager
上午敲代码时出现这个问题,简单记录一下解决办法,有时间详细描述一下深层原因. 问题出现在这: @Override public void onSaveInstanceState(Bundle outS ...
- ERP渠道信息的修改和渠道联系记录(二十三)
用例图: 前端代码: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Cha ...
- EntityFrameWork 图解
- (转)jquery serialize表单序列化,当radio或checkbox 未选中时,没有序列化到对象中的原因分析和解决方案 - ghostsf
相信很多人都用过jq的表单序列化serialize()方法,因为这能很方便地帮你把表单里所有的非禁用输入控件序列化为 key/value 对象,不需要你再去一个个地拼接参数了. 这是一个很好用的函数, ...
- 使用VS2013、TFS2013和Git进行分布式团队协作
题记:呵呵,首先声明,题目起的有点大,其实我只想介绍下VS2013和TFS2013新加入的Git功能,也不是在VS中使用Git的详细向导(以后有空再详细分享给大家).这篇文章虽然在写这篇文章<V ...
- 2015 ACM Amman Collegiate Programming Contest 题解
[题目链接] A - Who Is The Winner 模拟. #include <bits/stdc++.h> using namespace std; int T; int n; s ...
- WIN10下 VS2017+OpenCv 3.4.1 配置
写篇博客来记录一下opencv在VS中的配置. 一.下载OpenCv安装包 下载的途径有三种: 1.官网下载 但是官网下载真的是贼头大,首先下载好好的突然说下载中断,而且无法恢复,此外,还慢,毕竟外网 ...
- 干货: 可视化项目实战经验分享,轻松玩转 Bokeh (建议收藏)
作者 | Will Koehrsen 翻译 | Lemon 译文出品 | Python数据之道 (ID:PyDataRoad) 本文通过一个项目案例,详细的介绍了如何从 Bokeh 基础到构建 Bok ...
- BZOJ 3564: [SHOI2014]信号增幅仪 最小圆覆盖
3564: [SHOI2014]信号增幅仪 题目连接: http://www.lydsy.com/JudgeOnline/problem.php?id=3564 Description 无线网络基站在 ...
- JavaMail发送和接收邮件API(详解)
一.JavaMail概述: JavaMail是由Sun定义的一套收发电子邮件的API,不同的厂商可以提供自己的实现类.但它并没有包含在JDK中,而是作为JavaEE的一部分. 厂商所提供的JavaMa ...