美文网首页
Java 8:集合类转换(List转换为Map..)

Java 8:集合类转换(List转换为Map..)

作者: RealityVibe | 来源:发表于2019-10-06 12:00 被阅读0次

    集合转换

    List转换为Map

    • value为List<Apple>
    // List<Apple> 根据color转换为map
    Map<String, List<Apple>> appleMap = apples.stream().collect(groupingBy(Apple::getColor));
    
    • value为Apple
    // List<Apple> 根据color转换为map<String, Apple>,重复的Color取后者
    Map<String, Apple> appleMap = apples.stream().collect(toMap(Apple::getColor, a -> a, (a1, a2) -> a2));
    
    • value为Apple的属性
    // List<Apple> 根据color转换为map<String, Integer>,重复的Color取后者
    Map<String, Integer> map2 = apples.stream().collect(toMap(Apple::getColor, Apple::getWeight, (a1, a2) -> a2));
    

    Map转List

    Map<String, Apple> appleMap = apples.stream().collect(toMap(Apple::getColor, a -> a, (a1, a2) -> a2));
    // map转List
    List<String> colors = appleMap.values().stream().map(Apple::getColor).collect(toList());
    

    Map转Set

    Map<String, Apple> appleMap = apples.stream().collect(toMap(Apple::getColor, a -> a, (a1, a2) -> a2));
    // map转set
    Set<String> set = appleMap.values().stream().map(Apple::getColor).collect(toSet());
    

    相关文章

      网友评论

          本文标题:Java 8:集合类转换(List转换为Map..)

          本文链接:https://www.haomeiwen.com/subject/cjjupctx.html