Java 8流映射分组操作

时间:2017-10-18 09:28:46

标签: java lambda java-8 java-stream

我有两节课:

Person

public class Person {

    private final Long id;
    private final String address;
    private final String phone;

    public Person(Long id, String address, String phone) {
        this.id = id;
        this.address = address;
        this.phone = phone;
    }

    public Long getId() {
        return id;
    }

    public String getAddress() {
        return address;
    }

    public String getPhone() {
        return phone;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", address=" + address + ", phone=" + phone + "]";
    }
}

CollectivePerson

import java.util.HashSet;
import java.util.Set;

public class CollectivePerson {

    private final Long id;
    private final Set<String> addresses;
    private final Set<String> phones;

    public CollectivePerson(Long id) {
        this.id = id;
        this.addresses = new HashSet<>();
        this.phones = new HashSet<>();
    }

    public Long getId() {
        return id;
    }

    public Set<String> getAddresses() {
        return addresses;
    }

    public Set<String> getPhones() {
        return phones;
    }

    @Override
    public String toString() {
        return "CollectivePerson [id=" + id + ", addresses=" + addresses + ", phones=" + phones + "]";
    }
}

我想进行流操作,以便:

  • Person映射到CollectivePerson
  • address的{​​{1}}和phone分别合并到Personaddresses phones所有CollectivePerson s具有相同的Person

我为此目的编写了以下代码:

id

它完成工作并输出为:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class Main {

    public static void main(String[] args) {
        Person person1 = new Person(1L, "Address 1", "Phone 1");
        Person person2 = new Person(2L, "Address 2", "Phone 2");
        Person person3 = new Person(3L, "Address 3", "Phone 3");
        Person person11 = new Person(1L, "Address 4", "Phone 4");
        Person person21 = new Person(2L, "Address 5", "Phone 5");
        Person person22 = new Person(2L, "Address 6", "Phone 6");

        List<Person> persons = new ArrayList<>();
        persons.add(person1);
        persons.add(person11);
        persons.add(person2);
        persons.add(person21);
        persons.add(person22);
        persons.add(person3);

        Map<Long, CollectivePerson> map = new HashMap<>();
        List<CollectivePerson> collectivePersons = persons.stream()
                .map((Person person) -> {
                    CollectivePerson collectivePerson = map.get(person.getId());

                    if (Objects.isNull(collectivePerson)) {
                        collectivePerson = new CollectivePerson(person.getId());
                        map.put(person.getId(), collectivePerson);

                        collectivePerson.getAddresses().add(person.getAddress());
                        collectivePerson.getPhones().add(person.getPhone());

                        return collectivePerson;
                    } else {
                        collectivePerson.getAddresses().add(person.getAddress());
                        collectivePerson.getPhones().add(person.getPhone());

                        return null;
                    }
                })
                .filter(Objects::nonNull)
                .collect(Collectors.<CollectivePerson>toList());

        collectivePersons.forEach(System.out::println);
    }
}

但我相信可能有一种更好的方式,分组方式实现同​​样的目标。任何指针都会很棒。

4 个答案:

答案 0 :(得分:5)

您可以将Collectors.toMap与合并功能结合使用:

public static <T, K, U, M extends Map<K, U>>
Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper,
                            Function<? super T, ? extends U> valueMapper,
                            BinaryOperator<U> mergeFunction,
                            Supplier<M> mapSupplier)

映射如下所示:

Map<Long,CollectivePerson> collectivePersons =
  persons.stream()
         .collect(Collectors.toMap (Person::getId,
                                    p -> {
                                      CollectivePerson cp = new CollectivePerson (p.getId());
                                      cp.getAddresses().add (p.getAddress());
                                      cp.getPhones().add(p.getPhone());
                                      return cp;
                                    },
                                    (cp1,cp2) -> {
                                      cp1.getAddresses().addAll(cp2.getAddresses());
                                      cp1.getPhones().addAll(cp2.getPhones());
                                      return cp1;
                                    },
                                    HashMap::new));

您可以使用以下方法轻松从List<CollectivePerson>中提取Map

new ArrayList<>(collectivePersons.values())

以下是您的示例输入的输出Map

{1=CollectivePerson [id=1, addresses=[Address 1, Address 4], phones=[Phone 1, Phone 4]], 
 2=CollectivePerson [id=2, addresses=[Address 2, Address 6, Address 5], phones=[Phone 5, Phone 2, Phone 6]], 
 3=CollectivePerson [id=3, addresses=[Address 3], phones=[Phone 3]]}

答案 1 :(得分:3)

您应该使用收集器,而不是操纵外部Map。有toMapgroupingBy,两者都允许解决问题,但由于您的类设计有点冗长。主要障碍是缺少现有方法,将Person合并到CollectivePerson或从给定CollectivePerson实例构造Person,或者合并方法两个CollectivePerson个实例。

使用内置收集器的一种方法是

List<CollectivePerson> collectivePersons = persons.stream()
    .map(p -> {
        CollectivePerson cp = new CollectivePerson(p.getId());
        cp.getAddresses().add(p.getAddress());
        cp.getPhones().add(p.getPhone());
        return cp;
    })
    .collect(Collectors.collectingAndThen(Collectors.toMap(
        CollectivePerson::getId, Function.identity(),
        (cp1, cp2) -> {
            cp1.getAddresses().addAll(cp2.getAddresses());
            cp1.getPhones().addAll(cp2.getPhones());
            return cp1;
        }),
      m -> new ArrayList<>(m.values())
    ));

但在这种情况下,自定义收集器可能更简单:

Collection<CollectivePerson> collectivePersons = persons.stream()
    .collect(
        HashMap<Long,CollectivePerson>::new,
        (m,p) -> {
            CollectivePerson cp=m.computeIfAbsent(p.getId(), CollectivePerson::new);
            cp.getAddresses().add(p.getAddress());
            cp.getPhones().add(p.getPhone());
        },
        (m1,m2) -> m2.forEach((l,cp) -> m1.merge(l, cp, (cp1,cp2) -> {
            cp1.getAddresses().addAll(cp2.getAddresses());
            cp1.getPhones().addAll(cp2.getPhones());
            return cp1;
        }))).values();

两者都将从预定义方法中受益,以合并两个CollectivePerson实例,而第一个变体也将受益于CollectivePerson(Long id, Set<String> addresses, Set<String> phones)构造函数,甚至更好,CollectivePerson(Person p)构造函数,而第二个变体受益于CollectivePerson.add(Person p)方法......

请注意,第二个变量会返回Collection值的Map视图而不进行复制。如果你确实需要一个List,你可以像使用new ArrayList<>( «map» .values())一样简单地收缩它,就像整理器功能中的第一个变体一样。

答案 2 :(得分:1)

使用groupBy收藏家对您的人进行分组!

List<CollectivePerson> list = persons.stream().collect(Collectors.groupingBy(Person::getId)).entrySet().stream().map(x -> {
    // map all the addresses from the list of persons sharing the same id
    Set<String> addresses = x.getValue().stream().map(Person::getAddress).collect(Collectors.toSet());
    // map all the phones from the list of persons sharing the same id
    Set<String> phones = x.getValue().stream().map(Person::getPhone).collect(Collectors.toSet());
    // declare this constructor that takes three parameters
    return new CollectivePerson(x.getKey(), addresses, phones);
}).collect(Collectors.toList());

为此,您需要添加此构造函数:

public CollectivePerson(Long id, Set<String> addresses, Set<String> phones) {
    this.id = id;
    this.addresses = addresses;
    this.phones = phones;
}

答案 3 :(得分:0)

Map<Long, CollectivePerson> map = persons.stream().
            collect(Collectors.groupingBy(Person::getId, 
                    Collectors.collectingAndThen(Collectors.toList(),
                            Main::downColl)));

使用方法参考从具有相同CollectivePerson的人员列表中创建id对象。

public static CollectivePerson downColl(List<Person> ps) {

    CollectivePerson cp = new CollectivePerson(ps.get(0).getId());          
    for (Person p:ps) {
        cp.getAddresses().add(p.getAddress());
        cp.getPhones().add(p.getPhone());
    }
    return cp;
}