1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| public class StreamMethod { // 提取集合中所有偶数并求和 @Test public void methodOne() { List<String> list = Arrays.asList("1", "2", "3", "4", "5"); int sum = list.stream() .mapToInt(s -> Integer.parseInt(s)) // convert element from string to int .filter(n -> n % 2 == 0) // get all even numbers .sum(); // sum to one int
System.out.println(sum); }
// 所有名字首字母大写 @Test public void methodTwo() { List<String> list = Arrays.asList("lily", "smith", "jackson"); List<String> newList = list.stream() .map(s -> s.substring(0, 1).toUpperCase() + s.substring(1)) // 按指定规则对每一个流数据进行转换 .collect(Collectors.toList()); // 对流数据进行收集,生成新的List/Set
System.out.println(newList); }
// 将所有奇数从大到小排序,且不许出现重复 @Test public void methodThree() { List<Integer> list = Arrays.asList(1,69,342,4,5,143,2134,5,4324,45,56); List<Integer> newList = list.stream().distinct() // 去除重复的数据 .filter(n -> n % 2 == 1) // 拿到奇数 .sorted((a, b) -> b - a) // 排序 .collect(Collectors.toList()); System.out.println(newList); } }
|