Java 8 Stream flatMap and group by code compiler error

前端 未结 2 538
情歌与酒
情歌与酒 2021-01-14 03:18
// given a set of Item objects, group them by the managers of creator and owners
Map> managersItems = 
    itemSet.parallelStream().fl         


        
相关标签:
2条回答
  • 2021-01-14 03:55

    You didn't do anything wrong. Eclipse compiler has problems with type inference that causes these issues. If Luna compatibility is important, you will have to add explicit types to lambda expressions. Try, for example, Map.Entry::<String,Item>getKey

    On another note, it's not necessary to convert a List to array to stream it. You can directly call users.stream(). But even creating the List isn't necessary. You can use Stream.concat(Stream.of(item.getCreator()), item.getOwners().stream()) instead (granted, it's a bit unwieldy).

    Finally (and most importantly), avoid using parallelStream with blocking code, such as looking up data in an external system. Parallel streams are designed to handle CPU-bound tasks.

    0 讨论(0)
  • 2021-01-14 04:05

    I was able to come up with this solution from Misha's answer. This is working with Eclipse Luna Java compiler

    Map<String, List<Item>> managersItems = itemSet
        .stream()
         .<Map.Entry<String, Item>> flatMap(item -> {
             return Stream.concat(Stream.of(item.getCreatorLogin()), item.getOwners().stream()).map(
                 user -> {
                     LdapUserInfo ldapUser = LdapUserInfoFactory.create(user);
                     String manager = ldapUser.getManagerLoginName();
                     return new AbstractMap.SimpleEntry<String, Item>(manager, info);
                 });
             })
        .collect(Collectors.groupingBy(Map.Entry<String, Item>::getKey,
                 Collectors.mapping(Map.Entry<String, Item>::getValue,
                 Collectors.toList())));
    
    0 讨论(0)
提交回复
热议问题