list stream流排序
时间: 2023-11-08 22:18:40 浏览: 93
要对一个list使用stream流进行排序,可以使用sorted()方法。在sorted()方法中,你可以选择传入一个Comparator对象来指定排序的方式。如果不传入Comparator对象,则会使用默认的排序方式进行排序。下面是几个例子:
1. 对list<Integer>进行正序排序:
```
List<Integer> list = new ArrayList<>();
list.add(50);
list.add(45);
list.add(25);
list.add(98);
list.add(32);
List<Integer> sortedList = list.stream().sorted().collect(Collectors.toList());
```
结果为:[25, 32, 45, 50, 98]
2. 对list<Integer>进行倒序排序:
```
List<Integer> list = new ArrayList<>();
list.add(50);
list.add(45);
list.add(45);
list.add(98);
list.add(32);
List<Integer> sortedList = list.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
```
结果为:[98, 50, 45, 45, 32]
3. 对List<Person>的元素根据属性值进行倒序排序:
```
Person p1 = new Person("张三", new BigDecimal("50.0"));
Person p2 = new Person("王五", new BigDecimal("25.0"));
Person p3 = new Person("李四", new BigDecimal("68.0"));
Person p4 = new Person("李四", new BigDecimal("17.0"));
Person p5 = new Person("张三", new BigDecimal("45.0"));
List<Person> list = new ArrayList<>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
List<Person> sortedList = list.stream().sorted(Comparator.comparing(Person::getSalary).reversed()).collect(Collectors.toList());
```
结果为:[{name='李四', salary=68.0}, {name='张三', salary=50.0}, {name='王五', salary=45.0}, {name='张三', salary=45.0}, {name='李四', salary=17.0}]
这些例子展示了不同类型的list如何通过stream流进行排序。你可以根据自己的需求来选择合适的排序方式。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
#### 引用[.reference_title]
- *1* *2* *3* [Stream的排序](https://blog.csdn.net/weixin_30345055/article/details/97817882)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *4* [java8 stream自定义分组求和并排序的实现](https://download.csdn.net/download/weixin_38613330/12743652)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文