java 8流展开或发出列表以获取单个值

KIC*_*KIC 4 java lambda java-8

我有一张这样的地图:

 Map<String, List<String>> map
Run Code Online (Sandbox Code Playgroud)

现在我想从地图值中获取所有列表条目,并将它们用作另一个地图中的键.

Map<String, String> newMap = map.entrySet()
  .stream()
  .fiter(somefilter -> true)
  .collect(Collectors.toMap(
      k -> k.getValue(), // I want to have every single value as key
      v -> v.getKey());
Run Code Online (Sandbox Code Playgroud)

有没有办法在Java 8流中"展开"数组?在MongoDB中,我会写这样的东西:

Map<String, String> newMap = map.entrySet()
  .stream()
  .fiter(somefilter -> true)
  .unwind(entry -> entry.getValue())
  .collect(Collectors.toMap(
      k -> k.getValue(), 
      v -> v.getKey());
Run Code Online (Sandbox Code Playgroud)

ass*_*ias 6

一种方法是创建值/键对的流(例如,使用数组)并将它们平面映射以进行收集:

 Map<String, String> newMap = map.entrySet().stream()
         .flatMap(e -> e.getValue().stream().map(s -> new String[] { s, e.getKey() }))
         .collect(toMap(array -> array[0], array -> array[1]));
Run Code Online (Sandbox Code Playgroud)

字符串数组虽然看起来有点hacky ......

  • 是的,这有效!很感谢.您可以使用`new AbstractMap.SimpleEntry <String,String>(s,e.getKey()))代替"hackisch"字符串数组. (2认同)