流操作集合:
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class TestUtil {public static void main(String[] args) {List<Integer> collect = Stream.of(Arrays.asList(1, 2), Arrays.asList(3, 4)).flatMap(s -> s.stream()).collect(Collectors.toList());System.out.println("合并集合:" + collect);List<String> replace = Stream.of("a", "b", "c", "d").map(s -> s.toUpperCase()).collect(Collectors.toList());System.out.println("a,b,c,d更换大写字母:" + replace);List<String> filter = Stream.of("a", "b", "c", "d").filter(s -> ! s.equals("a")).collect(Collectors.toList());System.out.println("a,b,c,d过滤排除字母a:" + filter);String result = replace.stream().collect(Collectors.joining(", ", "(", ")"));System.out.println("a,b,c,d集合拼接字符串:" + result);String min = Stream.of("a", "b", "c", "d").min((Comparator.comparing(s -> s))).get();System.out.println("a,b,c,d排序取最小值:" + min);Integer total = Stream.of(1, 2, 3, 4).reduce(0, (sum, number) -> sum + number);System.out.println("1, 2, 3, 4求和:" + total);}
}
打印:
合并集合:[1, 2, 3, 4]
a,b,c,d更换大写字母:[A, B, C, D]
a,b,c,d过滤排除字母a:[b, c, d]
a,b,c,d集合拼接字符串:(A, B, C, D)
a,b,c,d排序取最小值:a
1, 2, 3, 4求和:10
来自:java8函数式编程