Stream流
提供更好操作的集合庫
- Guava
- Apach Commons Collections
- lambdaj - Mario Fusco
初始操作
stream stream流
List<String> threeHighCaloricDishNames =
Dish.menu
.stream()
.filter(d->d.getCalories()>300)
.map(Dish::getName)
.limit(3)
.collect(Collectors.toList());
System.out.println(threeHighCaloricDishNames);
parallelStream 多核流
List<String> threeHighCaloricDishNames =
Dish.menu
.parallelStream()
.filter(d->d.getCalories()>300)
.map(Dish::getName)
.limit(3)
.collect(Collectors.toList());
System.out.println(threeHighCaloricDishNames);
Map進行流操作
Map<Integer,Integer> map = new HashMap<>(10);
map.put(1,10);
map.put(2,20);
map.put(3,30);
map.put(4,30);
map.entrySet()
.stream()
.forEach(var->{
val key = var.getKey();
val value = var.getValue();
System.out.println("key:"+key+" value:"+value);
});
中間操作
filter 篩選
map 提取
limit 截斷
sorted 排序
List<Integer> list = Arrays.asList(2, 4, 1, 3, 7, 5, 9, 6, 8,7);
List<Integer> sortedList = list.parallelStream()
.filter(number-> number>5)
.sorted( (i1, i2) -> i2.compareTo(i1) )
.collect(Collectors.toList());
System.out.println(sortedList);
distinct 去重
List<Integer> list1 = Arrays.asList(2, 4, 1, 3, 7, 5, 9, 6, 8,7);
List<Integer> sortedList = list1.parallelStream()
.filter(number-> number>5)
.sorted()
.distinct()
.collect(Collectors.toList());
終端操作
forEach遍歷
collect 返回集合
.collect(Collectors.toList());
count 返回long
long count =
Dish.menu.stream()
.filter(d->d.getCalories()>300)
.distinct()
.limit(3)
.count();
System.out.println(count);
菜單實體
package com.java8.stream.entity;
import lombok.Data;
import java.util.*;
@Data
public class Dish {
private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;
public Type getType() {
return type;
}
public enum Type { MEAT, FISH, OTHER }
public static final List<Dish> menu =
Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 400, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH));
}
打賞一下