如何使用流API在Java

如何使用流API在Java

本文介绍了如何使用流API在Java 8中映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我有列表< Person> 。每个都有列表< String> ,这是该人拥有的电话号码列表。

Ok, so I have a List<Person>. and each Person has a List<String> that is a list of phone numbers that that person owns.

所以这是基本结构:

public class Person {

    private String name;
    private List<String> phoneNumbers;

    // constructors and accessor methods

}

我想创建一个 Map< String,Person> ,其中密钥是该人拥有的每个电话号码,值是实际的人。

I would like to create a Map<String, Person> where the key is each phone number that the person owns, and the value is the actual person.

所以要更好地解释。如果我有列表< Person>

So to explain better. If I had this List<Person>:

Person bob = new Person("Bob");
bob.getPhoneNumbers().add("555-1738");
bob.getPhoneNumbers().add("555-1218");

Person john = new Person("John");
john.getPhoneNumbers().add("518-3718");
john.getPhoneNumbers().add("518-3115");
john.getPhoneNumbers().add("519-1987");

List<Person> list = new ArrayList<>();
list.add(bob);
list.add(john);

我调用了这个方法。它会给我以下 Map< String,Person>

and I invoked this method. It would give me the following Map<String, Person>

Map<String, Person> map = new HashMap<>();
map.put("555-1738", bob);
map.put("555-1218", bob);

map.put("518-3718", john);
map.put("518-3115", john);
map.put("519-1987", john);

我想知道如何使用流来实现这个目标 API,因为我已经知道如何使用来执行循环等。

I would like to know how to achieve this using the stream API, as I already know how I would do it using for loops and such.

推荐答案

如果您有名为的人员名单和一个名为 PhoneNumberAndPerson 的人(你)可以使用通用元组代替)

If you have list of persons called persons and a class called PhoneNumberAndPerson (you could use a generic Tuple or Pair instead)

以下是步骤:

对于每个人,请记下该人的每个电话号码。对于每个电话号码,创建 PhoneNumberAndPerson 的新实例,并将其添加到列表中。使用flatMap制作所有这些较小列表的单个列表。要从此列表中生成 Map ,您需要提供一个函数来从 PhoneNumberAndPerson 中提取密钥,并提供另一个要提取的函数一个来自同一个 PhoneNumberAndPerson

For each person, take each phone number of that person. For each of those phone numbers, create a new instance of PhoneNumberAndPerson and add that to a list. Use flatMap to make one single list of all these smaller lists. To make a Map out of this list you supply one function to extract a key from a PhoneNumberAndPerson and another function to extract a Person from that same PhoneNumberAndPerson.

persons.stream()
    .flatMap(person -> person.getPhoneNumbers().stream().map(phoneNumber -> new PhoneNumberAndPerson(phoneNumber, person)))
    .collect(Collectors.toMap(pp -> pp.getPhoneNumber(), pp -> pp.getPerson()));

这篇关于如何使用流API在Java 8中映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 02:30