List list = Arrays.asList(“apple”, “banana”, “orange”, “grape”); List filteredList = list.stream() .filter(s -> s.startsWith(“a”)) .collect(Collectors.toList());
使用map()方法对集合中的元素进行转换:
List list = Arrays.asList(1, 2, 3, 4, 5); List squaredList = list.stream() .map(i -> i * i) .collect(Collectors.toList());
使用reduce()方法对集合中的元素进行归约操作:
List list = Arrays.asList(1, 2, 3, 4, 5); int sum = list.stream() .reduce(0, (a, b) -> a + b);
使用forEach()方法对集合中的元素进行遍历操作:
List list = Arrays.asList(“apple”, “banana”, “orange”, “grape”); list.stream() .forEach(System.out::println);
使用sorted()方法对集合中的元素进行排序操作:
List list = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3); List sortedList = list.stream() .sorted() .collect(Collectors.toList());