2016-06-15 23 views
0

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!

Antwort

0

würde ich eine Multimap aus Guave verwenden und die Ergebnisse so sammeln:

// the input map 
Map<String, List<String>> lettersNumbers = new HashMap<>(); 
lettersNumbers.put("a", Arrays.asList("1", "2")); 

// the output multimap 
Multimap<String, String> result = 
    lettersNumbers.entrySet() 
        .stream() 
        .collect(ArrayListMultimap::create, 
          (map, entry) -> { 
           entry.getValue().forEach((val) -> 
            map.put(val, entry.getKey())); 
          }, 
          ArrayListMultimap::putAll); 

Die Multimap wird die umgekehrte Abbildung enthalten. Wenn Sie das Ergebnis in einem java.util.Map-Objekt haben möchten, verwenden Sie Multimap.asMap().

+0

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. –

Verwandte Themen