如何基于嵌套对象属性对列表进行排序 [英] How to sort list based on nested object property

查看:113
本文介绍了如何基于嵌套对象属性对列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java流的新手,我只想对对象的键进行排序.

I am new to Java streams and I just want to sort the keys for my object.

所以,我尝试这样的方法,它能起作用

So, I try something like this and it works

List<FooSelect> li= Arrays.stream(obj.getFoos().getFoo())  //Stream<Foo>
    .map(Foo::getSelect)                                   //Stream<FooSelect>
    .sorted(Comparator.comparing(FooSelect::getFoosKey))   //Stream<FooSelect>
    .collect(Collectors.toList());

这会根据我想要的内容进行排序.

This sorts it according to what I want.

但是我得到的结果在List<FooSelect>对象中,尽管我想要在List<Foo>中.

But the result I get is in List<FooSelect> object, though I want it in List<Foo>.

排序后如何更改映射?

我要在

//Stream<Foo> after it is sorted.

我想要类似的东西

List<Foo> li = same result of code above;


Class : FooSelect
just has some String fields
string FooKey
string FooTKey

以及该方法的getter和setter(其中一个是我正在排序的getFoosKey)

and getters and setters for that (one of them is getFoosKey by which I am sorting)

Class: Foo
private FooSelect select
private FooInsert insert

Foo(select, insert)

public FooSelect getSelect() {
return select; }

相同的设置方法.

推荐答案

您可以在Comparator.comparing中使用lambda表达式代替方法引用

You can use lambda expression in Comparator.comparing instead of method reference

List<Foo> res = foos.stream()             
                    .sorted(Comparator.comparing(fo->fo.getSelect().getFooKey()))
                    .collect(Collectors.toList());

对于排序,您甚至不需要流

For just sorting you don't even need stream

foos.sort(Comparator.comparing(fo->fo.getSelect().getFooKey()));

这篇关于如何基于嵌套对象属性对列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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