好了扯了一大堆概念,让我们来看看集合和流处理数据的方式
@Data
public class Dish {
private final String name;
private final boolean vegetarian; //是否是素菜
private final int calories; //卡路里
private final Type type;
private enum Type{
MEAT,FISH,OTHER;
}
public Dish(String name, boolean vegetarian, int calories, Type type) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
this.type = type;
}
}
List<Dish> menu = Arrays.asList(
new Dish("apple",true,50, Dish.Type.OTHER),
new Dish("chicken",false,350, Dish.Type.MEAT),
new Dish("rich",true,150, Dish.Type.OTHER),
new Dish("pizza",true,350, Dish.Type.OTHER),
new Dish("fish",false,250, Dish.Type.FISH),
new Dish("orange",true,70, Dish.Type.OTHER),
new Dish("banana",true,60, Dish.Type.OTHER));
@Test
public void test() throws Exception {
menu.sort(new Comparator<Dish>() {
@Override
public int compare(Dish o1, Dish o2) {
return o1.getCalories() - o2.getCalories();
}
});
for (int i = 0; i < 3; i++) {
System.out.println(menu.get(i));
}
}
@Test
public void test() throws Exception {
List<Dish> collect = menu
.stream()
.sorted(Comparator.comparing(Dish::getCalories))
.limit(3)
.collect(Collectors.toList());
for (Dish dish : collect) {
System.out.println(dish);
}
}
Stream<Dish> limit = menu.stream()
.sorted(Comparator.comparing(Dish::getCalories))
.limit(3);
List<Dish> collect1 = limit.collect(Collectors.toList());
//IllegalStateException: stream has already been operated upon or closed
List<Dish> collect2 = limit.collect(Collectors.toList());