简体   繁体   中英

Java Stream: how to traverse a map of list and collect data to list

I have a map

HashMap<String, List<SomeObject>> map = data();

I need to traverse the list of objects and map it to another object and then collect to another list of object. Sample code is below, How can I do it in a proper way?

 List<User> userList = new ArrayList<>();
 map.forEach((key, value) ->
    userList = value.stream()
                .filter(obj-> testSomeCondition(obj))
                .map(obj -> mapper.mapToUser(obj,key))
                .collect(Collectors.toList())
 );

you can achieve that using the following

List<User> userList = map.entrySet()
  .stream()
  .flatMap(entry -> entry.getValue().stream()
      .filter(object -> testSomeCondition(object))
      .map(object -> mapper.mapToUser(object, entry.getKey()))
  ).collect(Collectors.toList());

flatmap here returns a stream which basically has all elements of mapped stream (which is generated by mapper function, in this case, entry.getValue().stream() ) you can read more about that here

If performance is not a concern (due of sequential forEachOrdered ) and you're ok with using a side-effect function(add on mutable collection) This shoud work. (IMO more readable than nested streams)

 List<User> result = new ArrayList<>();
 map.forEach((key, value) -> {
           value
          .stream()
          .filter(this::testSomeCondition)
          .map(object -> mapper.mapToUser(object, key))
          .forEachOrdered(result::add);
       });
 public boolean testSomeCondition(Object object) {return true;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM