2017-06-14 37 views
2

我想將類型List<A>轉換爲List<B>。我可以用java 8 stream方法做到這一點嗎?Java 8 - 流轉換映射的值類型

Map< String, List<B>> bMap = aMap.entrySet().stream().map(entry -> { 
     List<B> BList = new ArrayList<B>(); 
     List<A> sList = entry.getValue(); 
     // convert A to B 
     return ???; Map(entry.getKey(), BList) need to return 
    }).collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue())); 

我試過這段代碼,但不能在map()裏面轉換它。

+2

您需要實例化一個新的'Map.Entry'。嘗試'返回新的AbstractMap.SimpleEntry <>(entry.getKey(),BList);' – marstran

+0

令牌上的語法錯誤「>」,SimpleEntry的無效名稱<'>' –

+0

解決。我的eclipse版本較低以使用它。 –

回答

2

您可以在map功能實例AbstractMap.simpleEntry並執行轉換。

E.g.下面的代碼轉換List<Integer>List<String>

Map<String, List<Integer>> map = new HashMap<>(); 
Map<String, List<String>> transformedMap = map.entrySet() 
    .stream() 
    .map(e -> new AbstractMap.SimpleEntry<String, List<String>>(e.getKey(), e.getValue().stream().map(en -> String.valueOf(en)).collect(Collectors.toList()))) 
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); 
4

如果我的理解正確,你有一個Map<String, List<A>>,你想將它轉換爲Map<String, List<B>>。你可以這樣做:

Map<String, List<B>> result = aMap.entrySet().stream() 
    .collect(Collectors.toMap(
     entry -> entry.getKey(),      // Preserve key 
     entry -> entry.getValue().stream()    // Take all values 
        .map(aItem -> mapToBItem(aItem)) // map to B type 
        .collect(Collectors.toList())  // collect as list 
     ); 
1

你可以做這樣的:

public class Sandbox { 

    public static void main(String[] args) { 
     Map<String, List<A>> aMap = null; 
     Map<String, List<B>> bMap = aMap.entrySet().stream().collect(toMap(
       Map.Entry::getKey, 
       entry -> entry.getValue().stream() 
         .map(Sandbox::toB) 
         .collect(toList()))); 
    } 

    private static B toB(A a) { 
     // add your conversion 
     return null; 
    } 

    class B {} 

    class A {} 
}