| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jopen
9年前发布

Java8 stream 学习3

原文  http://renchx.com/java8-stream2/
 

将结果收集到 Map 中

@Test      public void getResultToMap() {          Stream<String> stream = Stream.of("a", "b", "c", "da", "asdass");          Map<String, Integer> map = stream.collect(Collectors                  .toMap(String::toString, String::length));          System.out.println(map);      }

分组和分片

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

@Test      public void groupBy() {          Stream<Locale> stream = Stream.of(Locale.getAvailableLocales());          Map<String, List<Locale>> map = stream.collect(Collectors.groupingBy(Locale::getCountry));          Map<String, Set<Locale>> map2 = stream.collect(Collectors.groupingBy(Locale::getCountry,                  Collectors.toSet()));          Map<String, Long> map3 = stream.collect(Collectors.groupingBy(Locale::getCountry,                  Collectors.counting()));// 返回根据国家分组的语言个数的map          // Map<String, Long> map4 =          // citys.collect(Collectors.groupingBy(City::getState,          // Collectors.summingLong(City::getPopulation)));          // 模拟计算每个州下的城市人口数          // Map<String, City> map5 =          // citys.collect(Collectors.groupingBy(City::getState,          // Collectors.maxBy(Compartor.comparing(City::getPopulation))));          // 映射每个州人口最多的城市          Map<String, Set<String>> map6 = stream.collect(                  Collectors.groupingBy(Locale::getDisplayCountry,                  Collectors.mapping(Locale::getDisplayLanguage, Collectors.toSet())));            System.out.println(map);      }

元素类型流

Stream api 提供了原始类型流:

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

【参考资料】

  1. 写给大忙人看的Java SE 8

 本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1450166331110.html
Java8 Java开发