在 Java 中使用 stream.sorted() 对列表进行排序 [英] Sorting a list with stream.sorted() in Java

查看:47
本文介绍了在 Java 中使用 stream.sorted() 对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对从流中排序列表很感兴趣.这是我正在使用的代码:

I'm interested in sorting a list from a stream. This is the code I'm using:

list.stream()
    .sorted((o1, o2)->o1.getItem().getValue().compareTo(o2.getItem().getValue()))
    .collect(Collectors.toList());

我错过了什么吗?该列表随后未排序.

Am I missing something? The list is not sorted afterward.

它应该根据具有最低值的项目对列表进行排序.

It should sort the lists according to the item with the lowest value.

for (int i = 0; i < list.size(); i++)
{
   System.out.println("list " + (i+1));
   print(list, i);
}

和打印方法:

public static void print(List<List> list, int i)
{
    System.out.println(list.get(i).getItem().getValue());
}

推荐答案

这不像 Collections.sort() 参数引用被排序.在这种情况下,您只会得到一个排序的流,您需要收集它并最终分配给另一个变量:

This is not like Collections.sort() where the parameter reference gets sorted. In this case you just get a sorted stream that you need to collect and assign to another variable eventually:

List result = list.stream().sorted((o1, o2)->o1.getItem().getValue().
                                   compareTo(o2.getItem().getValue())).
                                   collect(Collectors.toList());

您刚刚错过了分配结果

这篇关于在 Java 中使用 stream.sorted() 对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆