在路上

 找回密码
 立即注册
在路上 站点首页 学习 查看内容

Java8 stream 学习3

2017-2-7 13:42| 发布者: zhangjf| 查看: 552| 评论: 0

摘要: 原文 http://renchx.com/java8-stream2/ 将结果收集到 Map 中 @Test public void getResultToMap() { StreamString stream = Stream.of(a, b, c, da, asdass); MapString, Integer map = stre ...
原文 http://renchx.com/java8-stream2/ 将结果收集到 Map 中
  1. @Test
  2. public void getResultToMap() {
  3. Stream<String> stream = Stream.of("a", "b", "c", "da", "asdass");
  4. Map<String, Integer> map = stream.collect(Collectors
  5. .toMap(String::toString, String::length));
  6. System.out.println(map);
  7. }
复制代码

分组和分片

groupingBy 会产生一个值为列表的 map 对象。

  1. @Test
  2. public void groupBy() {
  3. Stream<Locale> stream = Stream.of(Locale.getAvailableLocales());
  4. Map<String, List<Locale>> map = stream.collect(Collectors.groupingBy(Locale::getCountry));
  5. Map<String, Set<Locale>> map2 = stream.collect(Collectors.groupingBy(Locale::getCountry,
  6. Collectors.toSet()));
  7. Map<String, Long> map3 = stream.collect(Collectors.groupingBy(Locale::getCountry,
  8. Collectors.counting()));// 返回根据国家分组的语言个数的map
  9. // Map<String, Long> map4 =
  10. // citys.collect(Collectors.groupingBy(City::getState,
  11. // Collectors.summingLong(City::getPopulation)));
  12. // 模拟计算每个州下的城市人口数
  13. // Map<String, City> map5 =
  14. // citys.collect(Collectors.groupingBy(City::getState,
  15. // Collectors.maxBy(Compartor.comparing(City::getPopulation))));
  16. // 映射每个州人口最多的城市
  17. Map<String, Set<String>> map6 = stream.collect(
  18. Collectors.groupingBy(Locale::getDisplayCountry,
  19. Collectors.mapping(Locale::getDisplayLanguage, Collectors.toSet())));
  20. System.out.println(map);
  21. }
复制代码
元素类型流

Stream api 提供了原始类型流:

  1. @Test
  2. public void baseStream() {
  3. IntStream intStream = IntStream.of(1, 2, 3);
  4. int[] values = { 2, 3, 4, 5, 6, 7, 8, 9, 0, 1 };
  5. IntStream intStream2 = Arrays.stream(values, 2, 5);
  6. IntStream intStream3 = IntStream.range(0, 10);// 不包含上限
  7. IntStream intStream4 = IntStream.rangeClosed(0, 10);// 包含上限
  8. Stream<String> stream = Stream.of("a", "asd", "2s");
  9. IntStream intStream5 = stream.mapToInt(String::length);
  10. Stream<Integer> stream2 = intStream2.boxed();// 原生流转换成对象流
  11. intStream2.forEach(System.out::println);
  12. }
复制代码

【参考资料】

写给大忙人看的Java SE 8

最新评论

小黑屋|在路上 ( 蜀ICP备15035742号-1 

;

GMT+8, 2025-7-9 09:12

Copyright 2015-2025 djqfx

返回顶部