初始化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());
网友评论