Java 8获取列表中的所有元素 [英] Java 8 get all elements in list

查看:585
本文介绍了Java 8获取列表中的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象列表,其中每个对象返回 List< String>
如何使用Java 8流只获得一个 List< String>

I have a List of Objects where each object that returns List<String>. How can I use Java 8 streams to get only one List<String>?

联系 class有以下方法;

Contact class has the following method;

public List<String> getSharedFriendsIds() {
    return sharedFriendsIds;
}

我有

List<Contact> contactsList;

我在尝试的是

List<String> sharedContacts = contactsList.stream()
    .map(Contact::getSharedFriendsIds)
    .sequential()
    .collect(Collectors.toList());

但是上面的行没有返回 List< String> 而是列表< List< String>> 这不是我想要的。

But above line is not returning List<String> but rather List<List<String>> which is not what I want.

推荐答案

您应该使用 .flatMap()来创建单个列表来自 sharedFriendsIds 列表,该列表包含在主列表中每个 Contact 对象 contactsList 。请检查以下内容;

You should use .flatMap() to create a single list from the sharedFriendsIds list that is contained in each Contact object from the main list contactsList. Please check the following;

List<String> sharedContacts = contactsList.stream()
        .filter(contacts -> contacts.getSharedFriendsIds() != null)
        .flatMap(contacts -> contacts.getSharedFriendsIds().stream())
        .sorted().collect(Collectors.toList());

.filter()致电是在列表中与 sharedFriendsIds == null 有任何联系的情况下,由于这会导致下一行中的NPE,我们应该将其过滤掉。还有其他方法可以实现这一点;

The .filter() call is for the case when there is any contact with sharedFriendsIds == null in the list, since that would cause NPE in the next line, we ought to filter those out. There are other ways to achieve that like;

List<String> sharedContacts = contactsList.stream()
        .flatMap(contacts -> Optional.ofNullable(contacts.getSharedFriendsIds())
                .map(List::stream).orElseGet(Stream::empty))
        .sorted().collect(Collectors.toList());

过滤null sharedFriendsIds 已完成以这种方式将它们作为空流吸收到 flatMap 逻辑中。

Where the filtering of null sharedFriendsIds are done in such a way that they are absorbed into the flatMap logic as empty streams.

你还用 .sequential 对于排序逻辑,我想,你应该使用 .sorted 方法,因为顺序是用于触发非并行用法,已经是默认 Stream 的默认配置。

Also you used .sequential for the sort logic, I guess, you should've used .sorted method, since sequential is for triggering non-parallel usage, which is already the default configuration of a default Stream.

这篇关于Java 8获取列表中的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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