美文网首页
Java collection备忘

Java collection备忘

作者: menglj | 来源:发表于2019-05-16 09:43 被阅读0次

    初始化ArrayList

    List<String> list = new ArrayList<String>(Arrays.asList(
            "a","b","c"
        ));
    

    把Iterable变为Collection

    在java8里可以参考下面的方法:

    Iterable<T> source = ...;
    List<T> target = new ArrayList<>();
    source.forEach(target::add);
    

    初始化map的方法

    Map<String, Integer> left = ImmutableMap.of("a", 1, "b", 2, "c", 3);
    //或者
    Map<String, String> test = ImmutableMap.<String, String>builder()
        .put("k1", "v1")
        .put("k2", "v2")
        ...
        .build();
    

    stream

    使用stream可以简化容器操作

    list to map [3][4]

    List<Hosting> list = new ArrayList<>();
    list.add(new Hosting(1, "liquidweb.com", 80000));
    list.add(new Hosting(2, "linode.com", 90000));
    list.add(new Hosting(3, "digitalocean.com", 120000));
    list.add(new Hosting(4, "aws.amazon.com", 200000));
    list.add(new Hosting(5, "mkyong.com", 1));
    
    Map<Integer, String> result3 = list.stream()
            .collect(Collectors.toMap(x -> x.getId(), x -> x, (oldValue,newValue) -> oldValue));
    

    list to list [5]

    List<Integer> nums = Arrays.asList(1, 2, 3, 4);
    List<Integer> squareNums = nums.stream()
            .map(n -> n * n)
            .collect(Collectors.toList());
    

    参考文档

    1. Easy way to change Iterable into Collection
    2. JAVA构造MAP并初始化MAP
    3. Java 8 将List转换为Map
    4. 一次Collectors.toMap的问题
    5. Java 8 中的 Streams API 详解

    相关文章

      网友评论

          本文标题:Java collection备忘

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