1,筛选数据
List<String> list = Arrays.asList("apple", "banana", "orange", "grapefruit", "kiwi"); list.stream() .filter(s -> s.length() >= 5) .forEach(System.out::println);
2,将集合中的每个字符串转换为大写,并收集到新的列表中:
List<String> list = Arrays.asList("apple", "banana", "orange", "grapefruit", "kiwi"); List<String> resultList = list.stream() .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(resultList);
3.统计集合中以字母"a"开头的字符串的数量:
List<String> list = Arrays.asList("apple", "banana", "orange", "grapefruit", "kiwi"); long count = list.stream() .filter(s -> s.startsWith("a")) .count(); System.out.println(count);
4.使用并行流来提高处理速度,筛选出长度小于等于5的字符串
List<String> list = Arrays.asList("apple", "banana", "orange", "grapefruit", "kiwi"); list.parallelStream() .filter(s -> s.length() <= 5) .forEach(System.out::println);
5.使用 Stream 对集合中的整数求和:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); int sum = numbers.stream() .mapToInt(Integer::intValue) .sum(); System.out.println(sum);