Collectors.reducing to List

可紊 提交于 2020-06-25 10:15:07

问题


Consider this class:

@Data
@AllArgsConstructor
@NoArgsConstructor
class User {
    String name;
    String languages;
}

I have a List<User> and I would like to reduce on languages. Input:

List<User> list = new ArrayList<>();
list.add(new User("sam", "java"));
list.add(new User("sam", "js"));
list.add(new User("apollo", "html"));

Expected output:

[User(name=apollo, languages=html), User(name=sam, languages=java, js)]

I can achieve this using following code:

List<User> l = list.stream()
    .collect(Collectors.groupingBy(
         u -> u.name,
         Collectors.reducing((u1, u2) -> 
             new User(u1.name, u1.languages + ", " + u2.languages))))
    .values()
    .stream()
    .filter(user -> user.get() != null)
    .map(user -> user.get())
    .collect(Collectors.toList());

System.out.println(l);

But I don't want to create two stream, can this be achieved using a single stream?


回答1:


But I don't want to create two stream, can this be achieved using a single stream?

Of course it is possible, you have two options and in both you have to use Collect.collectingAndThen that extracts the correct value type from a created Map.

You need to use the following lambda expression first:

BinaryOperator<User> binaryOperator = (u1, u2) -> 
    new User(u1.getName(), String.join(", ", u1.getLanguages(), u2.getLanguages()));

The solutions:

  1. Collectors.toMap with Collectors.collectingAndThen extracting values from the Map<String, User>:

    List<User> l = list.stream()                                       // Stream<User>
        .collect(Collectors.collectingAndThen(
            Collectors.toMap(                                          // Map
                User::getName,                                         // ..name as key
                user -> new User(user.getName(), user.getLanguages()), // ..value as user
                binaryOperator),                                       // ..combined
            map -> new ArrayList<>(map.values())));                    // extracted value
    
  2. Collectors.groupingBy with Collectors.collectingAndThen extracting values from the Map<String, Optional<User>> caused by Collectors.reducing:

    List<User> ll = list.stream()                     // Stream<User>
        .collect(Collectors.collectingAndThen(
            Collectors.groupingBy(                    // Map<String, Optional<User>>
                User::getName,                        // ... name as key
                Collectors.reducing(binaryOperator)), // ... reduced value
            map -> map.values().stream()              // extracted value
                .filter(Optional::isPresent)          // ... where is Optional present
                .map(Optional::get)                   // ... get it
                .collect(Collectors.toList())));      // ... create a List<User>
    

Note I suppose you use java-8, there might be a different solution using java-11 or higher.




回答2:


You can use Collectors.toMap():

List<User> l = new ArrayList<> (list.stream()
    .collect(Collectors.toMap(u -> u.name,
                              u -> new User (u.name,u.languages),
                              (u1, u2) -> new User(u1.name, u1.languages + ", " + u2.languages)))
    .values());


来源:https://stackoverflow.com/questions/61927722/collectors-reducing-to-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!