有篇文章讲的很仔细:Java 8中stream相关用法
1.创建stream
public static void main(String[] args) {
//1 Stream.of()
Stream<Integer> stream = Stream.of(9,5,2,7);
//2 Collection.stream()
stream = Arrays.asList(9,5,2,7).stream();
}
2.中间操作:filter、map、limit、sorted、distinct
public static void main(String[] args) {
//filter
Stream<Integer> stream = Stream.of(9,5,2,7,2);
stream.filter(n -> n > 5).forEach(System.out::println);//9 7
//map
stream = Stream.of(9,5,2,7,2);
stream.map(n -> n + 1).forEach(System.out::println); //10 6 3 8 3
//limit
stream = Stream.of(9,5,2,7,2);
stream.limit(3).forEach(System.out::println); //9 5 2
//sorted
stream = Stream.of(9,5,2,7,2);
stream.sorted().forEach(System.out::println); //2 2 5 7 9
//distinct
stream = Stream.of(9,5,2,7,2);
stream.distinct().forEach(System.out::println); //9 5 2 7
}
3.最终操作:foreach、count、collect
public static void main(String[] args) {
//foreach
Stream<Integer> stream = Stream.of(9,5,2,7,2);
stream.filter(n -> n > 5).forEach(System.out::println);//9 7
//count
stream = Stream.of(9,5,2,7,2);
stream.filter(n -> n > 5).count(); //2
//collect
stream = Stream.of(9,5,2,7,2);
stream.filter(n -> n > 5).collect(Collectors.toList());//List[9,7]
}
4.Map的putIfAbsent(非stream):putIfAbsent、computeIfAbsent、forEach
public static void main(String[] args) {
Map<String,Integer> map = new HashMap<String,Integer>();
map.putIfAbsent("a", 1);
map.computeIfAbsent("b", k -> {
int a = 1, b = 2;
return a + b;
});
map.forEach((k,v) -> System.out.println(k+":"+v));
}