简体   繁体   English

如何将 Map 的 Map 转换为 Java 中的列表

[英]How to convert Map of Map into list in java

I have a map of the map.我有地图的地图。 I have to convert into a list of an object using lambda.我必须使用 lambda 转换为对象列表。 I am trying to convert with Java 8.我正在尝试使用 Java 8 进行转换。

 private Map<Integer, Map<Integer, Movie>> movies; // given

 List<Movie> movies // expected

You can use declarative solution by using stream API like that:您可以通过使用像这样的流 API 来使用声明式解决方案:

List<Movie> movieList = movies.entrySet().stream()
                .flatMap(s-> s.getValue().entrySet().stream())
                .map(Map.Entry::getValue)
                .collect(Collectors.toList());

Alternatively you could call Map#values and avoid some lambda expressions, which could make your snippet more readable:或者,您可以调用Map#values并避免使用一些 lambda 表达式,这可以使您的代码段更具可读性:

List<Movie> movieList = movies.values()
                                .stream()
                                .map(Map::values)
                                .flatMap(Collection::stream)
                                .collect(Collectors.toList());

To get a single collection of Movie objects from the wrapping map, flatMap should be applied to the collection of values:要从包装贴图中获取单个Movie对象集合,应将flatMap应用于值集合:

Map<Integer, Map<Integer, Movie>> movieMap; 

List<Movie> movies = movieMap.values().stream() // Stream<Map<Integer, Movie>>
        .map(Map::values)  // Stream<Collection<Movie>>
        .flatMap(Collection::stream) // Stream<Movie>
        .collect(Collectors.toList());

However, the resulting list is likely to contain duplicate movies.但是,结果列表很可能包含重复的电影。 If the redundant duplicates need to be filtered, then distinct operation should be applied before .collect :如果需要过滤多余的重复项,则应在.collect之前应用distinct操作:

List<Movie> distinctMovies = movieMap.values().stream() // Stream<Map<Integer, Movie>>
        .map(Map::values)  // Stream<Collection<Movie>>
        .flatMap(Collection::stream) // Stream<Movie>
        .distinct()
        .collect(Collectors.toList());

Or the result may be collected into a set using .collect(Collectors.toSet()) :或者可以使用.collect(Collectors.toSet())将结果收集到一个集合中:

Set<Movie> movieSet = movieMap.values().stream() // Stream<Map<Integer, Movie>>
        .map(Map::values)  // Stream<Collection<Movie>>
        .flatMap(Collection::stream) // Stream<Movie>
        .collect(Collectors.toSet());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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