JDK1.8新特性之Stream类初识

JDK1.8新特性之Stream类初识

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamDemo {

    public static void main(String[] args) {
	    Stream<String> stream = Stream.of("good", "good", "study", "day", "day", "up");
	    // forEach方法
    	    stream.forEach(System.out::println);

	    // filter方法(输出长度大于3的字符串)
	    stream.filter((s) -> s.length() > 3).forEach(System.out::println);

	    // distinct(去重复)
	    // stream.distinct().forEach(System.out::println);

	    // map映射操作,将字符串转大写后再输出
	    stream.map(s -> s.toUpperCase()).forEach(System.out::println);

	    // flatMap
	    Stream<List<Integer>> ss = Stream.of(Arrays.asList(1, 2, 3), Arrays.asList(5, 6));
	    ss.flatMap(list -> list.stream()).forEach(System.out::println);

	    // reduce,找出流中长度最大的字符串
	    Optional<String> opt = stream.reduce((s1, s2) -> s1.length() >= s2.length() ? s1 : s2);
	    System.out.println(opt.get());

	    // collect
	    List<String> list = stream.collect(Collectors.toList());
	    list.forEach(System.out::println);

	    // ::方法引用
	    // 引用静态方法:Integer.valueOf
	    // 引用实例方法:list::add
	    // 引用构造方法:ArrayList::new

    }
}
posted on 2019-05-22 17:43  行之间  阅读(208)  评论(0编辑  收藏  举报