1. 程式人生 > >jdk8-stream流

jdk8-stream流

 流操作集合:


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函數語言程式設計