Java8 stream 學習3
將結果收集到 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);
}</pre> <h2>元素類型流 </h2>
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);
}</pre><br />
【參考資料】
- 寫給大忙人看的Java SE 8
</ol>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!