Java collection备忘

初始化ArrayList

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

把Iterable变为Collection

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

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

初始化map的方法

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

stream

使用stream可以简化容器操作

list to map [3][4]

List 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 result3 = list.stream()
        .collect(Collectors.toMap(x -> x.getId(), x -> x, (oldValue,newValue) -> oldValue));

list to list [5]

List nums = Arrays.asList(1, 2, 3, 4);
List 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备忘)