リストの地図のうち、単一の値を取得する方法 - Javaの8?

ルカ:

私は地図を次しているMap<List<String>, String>次の例の値を持ちます:

List["Los Angeles", "New York", "Chicago"] -> "USA",
List["Toronto", "Vancover", "Montréal"] -> "Canada"

それは地図を取得することが可能であるMap<String, String>し、それのキーに値リストのすべての要素をマッピング?例:

"Los Angeles" -> "USA",
"New York" -> "USA",
"Chicago" -> "USA",
"Toronto" -> "Canada",
...

私はあとがき私は並べ替えることができ、ストリームにそれを必要とします。

ガーボルBakos:

もちろんそれは可能です:

 Map<List<String>, String> map = new HashMap<>();
    map.put(List.of("Los Angeles", "New York", "Chicago"), "USA");
    map.put(List.of("Toronto", "Vancover", "Montréal"), "Canada");

    Map<String, String> newMap = map.entrySet().stream().flatMap(entry -> entry.getKey().stream().map(city -> Map.entry(city, entry.getValue()))).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));

出力例:

{=カナダ、シカゴ= USA、Vancover =カナダ、ロサンゼルス=米国、カナダのトロント=ニューヨーク= USA、モントラ©}

まず、あなたがする必要がありますflatMapentrySetStreamあなたができるmap新しいの鍵Stream例えばエントリのを。

あなたは、あなたのようにそれを必要と言及したようStreamなので、おそらくあなたは前に停止しますcollect

map.entrySet().stream()
  .flatMap(entry -> entry.getKey().stream()
    .map(city -> Map.entry(city, entry.getValue())))

(これらのエントリは新しいに収集することができますMap。)

おすすめ

転載: http://10.200.1.11:23101/article/api/json?id=4991&siteId=1