Java 8 list 对象字段升序降序
原文:https://www.concretepage.com/java/jdk-8/java-8-stream-sorted-example
Stream sorted() using Natural Ordering, Comparator and Reverse Ordering
Find the syntax of sorted()
method.
1. sorted()
: It sorts the elements of stream using natural ordering. The element class must implement Comparable
interface.
2. sorted(Comparator<? super T> comparator)
: Here we create an instance of Comparator
using lambda expression. We can sort the stream elements in ascending and descending order.
The following line of code will sort the list in natural ordering.
list.stream().sorted()
To reverse the natural ordering Comparator
provides reverseOrder()
method. We use it as follows.
list.stream().sorted(Comparator.reverseOrder())
The following line of code is using Comparator
to sort the list.
list.stream().sorted(Comparator.comparing(Student::getAge))
To reverse the ordering, Comparator
provides reversed()
method. We use this method as follows.
list.stream().sorted(Comparator.comparing(Student::getAge).reversed())
Stream sorted() with List
Here we are sorting a List
of objects of Student
class. First we will sort by natural ordering and then using Comparator
. We will reverse both ordering natural ordering as well as ordering provided by Comparator
in our example.
SortList.java
package com.concretepage; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; public class SortList {public static void main(String[] args) {List<Student> list = new ArrayList<Student>();list.add(new Student(1, "Mahesh", 12));list.add(new Student(2, "Suresh", 15));list.add(new Student(3, "Nilesh", 10));System.out.println("---Natural Sorting by Name---");List<Student> slist = list.stream().sorted().collect(Collectors.toList());slist.forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge()));System.out.println("---Natural Sorting by Name in reverse order---");slist = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());slist.forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge())); System.out.println("---Sorting using Comparator by Age---");slist = list.stream().sorted(Comparator.comparing(Student::getAge)).collect(Collectors.toList());slist.forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge()));System.out.println("---Sorting using Comparator by Age with reverse order---");slist = list.stream().sorted(Comparator.comparing(Student::getAge).reversed()).collect(Collectors.toList());slist.forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge()));} }
Student.java
package com.concretepage; public class Student implements Comparable<Student> {private int id;private String name;private int age;public Student(int id, String name, int age) {this.id = id;this.name = name;this.age = age;}public int getId() {return id;}public String getName() {return name;}public int getAge() {return age;}@Overridepublic int compareTo(Student ob) {return name.compareTo(ob.getName());}@Overridepublic boolean equals(final Object obj) {if (obj == null) {return false;}final Student std = (Student) obj;if (this == std) {return true;} else {return (this.name.equals(std.name) && (this.age == std.age));}}@Overridepublic int hashCode() {int hashno = 7;hashno = 13 * hashno + (name == null ? 0 : name.hashCode());return hashno;} }
Output
---Natural Sorting by Name--- Id:1, Name: Mahesh, Age:12 Id:3, Name: Nilesh, Age:10 Id:2, Name: Suresh, Age:15 ---Natural Sorting by Name in reverse order--- Id:2, Name: Suresh, Age:15 Id:3, Name: Nilesh, Age:10 Id:1, Name: Mahesh, Age:12 ---Sorting using Comparator by Age--- Id:3, Name: Nilesh, Age:10 Id:1, Name: Mahesh, Age:12 Id:2, Name: Suresh, Age:15 ---Sorting using Comparator by Age with reverse order--- Id:2, Name: Suresh, Age:15 Id:1, Name: Mahesh, Age:12 Id:3, Name: Nilesh, Age:10
Stream sorted() with Set
Here we are sorting the Set
of objects of Student
class. This class must override equals()
and hashCode()
methods to identify unique elements. For natural ordering Student
class needs to implement Comparable
interface. In our example we will sort our Set
using natural ordering as well as ordering provided by Comparator
.
SortSet.java
package com.concretepage; import java.util.Comparator; import java.util.HashSet; import java.util.Set; public class SortSet {public static void main(String[] args) {Set<Student> set = new HashSet<Student>();set.add(new Student(1, "Mahesh", 12));set.add(new Student(2, "Suresh", 15));set.add(new Student(3, "Nilesh", 10));System.out.println("---Natural Sorting by Name---");set.stream().sorted().forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge()));System.out.println("---Natural Sorting by Name in reverse order---");set.stream().sorted(Comparator.reverseOrder()).forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge())); System.out.println("---Sorting using Comparator by Age---");set.stream().sorted(Comparator.comparing(Student::getAge)).forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge()));System.out.println("---Sorting using Comparator by Age in reverse order---");set.stream().sorted(Comparator.comparing(Student::getAge).reversed()).forEach(e -> System.out.println("Id:"+ e.getId()+", Name: "+e.getName()+", Age:"+e.getAge()));} }
Output
---Natural Sorting by Name--- Id:1, Name: Mahesh, Age:12 Id:3, Name: Nilesh, Age:10 Id:2, Name: Suresh, Age:15 ---Natural Sorting by Name in reverse order--- Id:2, Name: Suresh, Age:15 Id:3, Name: Nilesh, Age:10 Id:1, Name: Mahesh, Age:12 ---Sorting using Comparator by Age--- Id:3, Name: Nilesh, Age:10 Id:1, Name: Mahesh, Age:12 Id:2, Name: Suresh, Age:15 ---Sorting using Comparator by Age in reverse order--- Id:2, Name: Suresh, Age:15 Id:1, Name: Mahesh, Age:12 Id:3, Name: Nilesh, Age:10
Stream sorted() with Map
Here we are sorting a Map
by key as well as value.
SortMap.java
package com.concretepage; import java.util.Comparator; import java.util.HashMap; import java.util.Map; public class SortMap {public static void main(String[] args) {Map<Integer, String> map = new HashMap<>();map.put(15, "Mahesh");map.put(10, "Suresh");map.put(30, "Nilesh");System.out.println("---Sort by Map Value---");map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).forEach(e -> System.out.println("Key: "+ e.getKey() +", Value: "+ e.getValue()));System.out.println("---Sort by Map Key---");map.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).forEach(e -> System.out.println("Key: "+ e.getKey() +", Value: "+ e.getValue()));} }
Output
---Sort by Map Value--- Key: 15, Value: Mahesh Key: 30, Value: Nilesh Key: 10, Value: Suresh ---Sort by Map Key--- Key: 10, Value: Suresh Key: 15, Value: Mahesh Key: 30, Value: Nilesh
Here we are sorting a map whose values are custom objects.
SortMapOfCustomObject.java
package com.concretepage; import java.util.Comparator; import java.util.HashMap; import java.util.Map; public class SortMapOfCustomObject {public static void main(String[] args) {Map<Integer, Student> map = new HashMap<>();map.put(1, new Student(1, "Mahesh", 12));map.put(2, new Student(2, "Suresh", 15));map.put(3, new Student(3, "Nilesh", 10));//Map Sorting by Value i.e student's natural ordering i.e by namemap.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getValue)).forEach(e -> {Integer key = (Integer)e.getKey();Student std = (Student)e.getValue();System.out.println("Key: " + key +", value: ("+ std.getId() +", "+ std.getName()+", "+ std.getAge()+")"); });} }
Output
Key: 1, value: (1, Mahesh, 12) Key: 3, value: (3, Nilesh, 10) Key: 2, value: (2, Suresh, 15)
Java 8 list 对象字段升序降序相关推荐
- Java的Comparator排序(升序降序)理解
Java的Comparator排序(升序降序)理解 int compare(T o1, T o2); 这里o1表示位于前面的对象,o2表示后面的对象 返回-1(或负数),表示不需要交换01和02的位置 ...
- Java中使用sort()进行升序降序排序
这篇文章主要介绍了详解Java sort()数组排序(升序和降序),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 我们在学习 J ...
- Java List集合排序,升序降序
在C#开发中,如果一个List集合需要进行重新排序,直接Orderby即可,但是在Java中,思路一样,但是写法不一样,特记录,方便各位码友学习使用. 自己使用版本 List<UserInfo& ...
- js,vue,javascript数组对象的升序降序方法封装
/*** @author lp* @desc 数组对象排序* sort会改变原数据,无需return* @param {arr:需要排序数据,column:参与排序字段,order:asc正序,des ...
- vue前端 数组如何通过时间字段升序降序
分享一个小知识点,不通过后端sql语句排序,借助前端接收后端的数组进行排序: 根据数组中的时间段排序 DemandApi.query(this.queryParam).then((res) => ...
- js:数组对象按key值进行升序降序排序
1.先定义一个数组对象 let arr=[{name:'李欣',age:'18'},{name:'王钊',age:'15'},{name:'李雪',age:'20'},{name:'李逍遥',age: ...
- html table表头升序 降序,jquery实现表格根据字段进行升序降序
例子: 蚂蚁部落 * { margin: 0; padding: 0; } body { padding: 100px; } .select { position: relative; display ...
- java中升序 降序怎么表示_Java sort()数组排序(升序和降序)
我们在学习 Java 的过程中肯定会遇到对数组进行升序或降序等排序问题,本节主要介绍如何实现 Java 数组的升序和降序.Java 语言使用 Arrays 类提供的 sort() 方法来对数组进行排序 ...
- java treemap value排序_Java TreeMap升序|降序排列和按照value进行排序的案例
TreeMap 升序|降序排列 import java.util.Comparator; import java.util.TreeMap; public class Main { public st ...
最新文章
- 全球3D机器视觉技术引领者,银牛微电子强势登陆中国市场
- h1.1 hadoop简介
- 全球及中国有机肥料行业投资价值与营销品牌战略报告2022版
- formal method lecture 2: propositional logic
- PostgreSQL开放自由
- n76e885_新唐N76E003,N76E616烧录,调试各种问题集【坑集】
- 【codevs1116】四色问题,深搜入门题目
- CIKM2021推荐系统论文集锦
- quartz的负载均衡
- MySQL 两个死锁样例
- 有微服务难题?你需要强大的网关!
- 如何在OTN网站下载Grid方法(Oracle RAC)
- 量子计算:一个即将破灭的泡沫?
- R语言绘制频数分布直方图或密度分布曲线
- NetFPGA-SUME10G以太网接口仿真问题
- 微信小程序observers数据监听器的使用
- vue 封装图片预览组件
- 实战 Vue 之生命周期钩子函数执行顺序
- 切比雪夫不等式证明及应用
- 重装系统后安装的软件
热门文章
- 视频提取音频 - 手机视频在线提取音频提取器
- Lookahead、LazyOptimizer、MaskedAdamOptimizer、AdaBound
- 互动媒体——随及行为以及运动学
- 古琴销售怎么做阳php学,古琴斫琴要领
- NoMachine出现 The session negotiation failed的解决方案及踩坑总结
- 爪哇国新游记之三十二----邮件发送
- 地球重力——黄金维教授,台湾交通大学
- 读论文 Automatic generation and detection of highly reliable fiducial markersnunder occlusion
- TinkerBoard-S 上手体验
- vr计算机方面的应用,AR和VR到底有什么区别,分别应用在哪些方面?