Lasst uns gesagt, dass ich eine Karte von String/Liste habenRevert Schlüssel/Wert-Karte
Map<String, List<String>> map = new HashMap<>();
map.put("product1", Arrays.asList("res1", "res2"));
map.put("product2", Arrays.asList("res1", "res2"));
Wo der Schlüssel einen Brief, und der Wert ist eine Liste von „Zahlen“
Jetzt Was ich versuche zu erreichen, ist, über die Karte zu iterieren und eine Karte mit "Nummer" als Schlüssel und "Buchstabe" als Wert zurückzugeben. So etwas wie
<"res1", List<"product1","product2" >>
<"res2", List<"product1","product2" >>
Vorerst schaffe ich es zu tun, aber in zwei Schritten, und der Code scheint ziemlich verbouse
@Test
public void test2() throws InterruptedException {
List<String> restrictions = Arrays.asList("res1", "res2");
Map<String, List<String>> productsRes = new HashMap<>();
productsRes.put("product1", restrictions);
productsRes.put("product2", restrictions);
ArrayListMultimap multiMap = productsRes.keySet()
.stream()
.flatMap(productId -> productsRes.get(productId)
.stream()
.map(restriction -> {
Multimap<String, List<String>> multimap = ArrayListMultimap.create();
multimap.put(restriction, Arrays.asList(productId));
return multimap;
}))
.collect(ArrayListMultimap::create, (map, restriction) -> map.putAll(restriction),
ArrayListMultimap::putAll);
Map<String, List<String>> resProducts = Multimaps.asMap(multiMap);
}
Jeder Vorschlag ?.
Danke!
Nur fyi: Guava hat bereits eine Methode, um das Mapping einer Multimap umzukehren, siehe http://stackoverflow.com/questions/3678601/how-to-do-map-inversion-with-guava-with-non-- Einzelwerte. –