在Java 8流中按属性排序 [英] Sorting by property in Java 8 stream

查看:685
本文介绍了在Java 8流中按属性排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哦,那些棘手的Java 8流与lambdas。它们非常强大,但错综复杂需要将一个标题包裹起来。

Oh, those tricky Java 8 streams with lambdas. They are very powerful, yet the intricacies take a bit to wrap one's header around it all.

假设我有一个用户输入属性 User.getName()。假设我有一个与名称相关联的用户 Map< String,User> 的地图(例如,登录用户名)。让我们进一步说我有一个比较器 UserNameComparator.INSTANCE 的实例来排序用户名(可能还有花哨的整理者等)。

Let's say I have a User type with a property User.getName(). Let's say I have a map of those users Map<String, User> associated with names (login usernames, for example). Let's further say I have an instance of a comparator UserNameComparator.INSTANCE to sort usernames (perhaps with fancy collators and such).

那么如何获取地图中的用户列表,按用户名排序?我可以忽略地图键并执行此操作:

So how do I get a list of the users in the map, sorted by username? I can ignore the map keys and do this:

return userMap.values()
    .stream()
    .sorted((u1, u2) -> {
      return UserNameComparator.INSTANCE.compare(u1.getName(), u2.getName());
    })
    .collect(Collectors.toList());

但我必须提取名称才能使用 UserNameComparator。 INSTANCE 似乎是太多的手工工作。有什么方法我可以简单地提供 User :: getName 作为一些映射函数,只是为了排序,仍然得到用户实例回到收集列表中?

But that line where I have to extract the name to use the UserNameComparator.INSTANCE seems like too much manual work. Is there any way I can simply supply User::getName as some mapping function, just for the sorting, and still get the User instances back in the collected list?

奖励:如果我想要排序的东西是两个级别,如用户怎么办? .getProfile()。getUsername()

Bonus: What if the thing I wanted to sort on were two levels deep, such as User.getProfile().getUsername()?

推荐答案

你想要的是 比较器#比较

What you want is Comparator#comparing:

userMap.values().stream()
    .sorted(Comparator.comparing(User::getName, UserNameComparator.INSTANCE))
    .collect(Collectors.toList());

对于问题的第二部分,您只需使用

For the second part of your question, you would just use

Comparator.comparing(
    u->u.getProfile().getUsername(), 
    UserNameComparator.INSTANCE
)

这篇关于在Java 8流中按属性排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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