package com.imooc.stream; import org.junit.Test; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; public class StreamMethod { //提取集合中所有的偶数并求和 @Test public void case1() { List<String> list = Arrays.asList("1", "2", "3", "4", "5", "12"); int sum = list.stream().mapToInt(s -> Integer.parseInt(s)).filter(n -> n % 2 == 0).sum();//提取stream对象并转化为整数并进行过滤求和 System.out.println(sum); } //所有名字首字母大写 @Test public void case2() { /** * map 按规则对每一个流进行转换 * collect 对流进行收集,生成新的list/set(生成没有重复) */ List<String> list = Arrays.asList("lily", "andy", "jackson", "smith"); //list.stream().map(s -> s.substring(0,1).toUpperCase() + s.substring(1)).forEach(s -> System.out.println(s)); List newList = list.stream().map(s -> s.substring(0, 1).toUpperCase() + s.substring(1)).collect(Collectors.toList()); System.out.println(newList); } //将所有奇数从大到小进行排序,且不允许重复 @Test public void case3() { /** * distinct 去吃重复 */ List<Integer> list = Arrays.asList(1, 5, 6, 7, 8, 9, 324, 5, 46, 2, 31, 31); List newList = list.stream().distinct().filter(n -> n % 2 == 1).sorted((a, b) -> b - a).collect(Collectors.toList()); System.out.println(newList); } }
标签:substring,常用,Stream,stream,list,List,System,003,Test From: https://www.cnblogs.com/LLL0617/p/17032563.html