Java 8将字符串列表转换为映射列表

ruh*_*ewo -3 java collections lambda java-8

我有List<List<String>>。我想根据内部List的特定元素将其转换为Map。

我试过了

ddList.stream().flatMap(x -> x.stream()
            .collect(Collectors.toMap(Function.identity(), String::length)));
Run Code Online (Sandbox Code Playgroud)

它不起作用。这是怎么了?

Era*_*ran 5

它应该是:

Map<String, Integer> sMap = 
    ddMap.stream()
         .flatMap(x -> x.stream())
         .collect(Collectors.toMap(Function.identity(),
                                   String::length));
Run Code Online (Sandbox Code Playgroud)

PS如果输入List包含任何重复的元素,则此代码将引发异常。您可以使用以下方法消除重复项distinct

Map<String, Integer> sMap = 
    ddMap.stream()
         .flatMap(x -> x.stream())
         .distinct()
         .collect(Collectors.toMap(Function.identity(),
                                   String::length));
Run Code Online (Sandbox Code Playgroud)

编辑:

根据您的评论,您根本不需要flatMap,但是像这样:

Map<String, List<String>> sMap = 
    ddMap.stream()
         .collect(Collectors.toMap(l -> l.get(0), // or some other member 
                                                  // of the inner List
                                   Function.identity()));
Run Code Online (Sandbox Code Playgroud)