流api
流api的使用
追加说明,现如今,你们可以发现,越来越多代码采用流api等形式,如果你还看不懂,或者还不会用那就out啦!!
List<Integer> integers = new ArrayList<>();
integers.add(1);
integers.add(3);
integers.add(2);
integers.add(10);
integers.add(8);
//integers.stream().forEach((n)-> System.out.println(n));
// Stream<Integer> oddStream = integers.stream().filter((n) -> (n % 2) == 1);
// oddStream.forEach((n)-> System.out.println(n));
Optional<Integer> maxValue = integers.stream().max(Integer::compare);
if (maxValue.isPresent()) {
System.out.println(maxValue.orElse(0));
}
//int reduceObj = integers.stream().reduce(1, (a,b) -> a*b);
/*if (reduceObj.isPresent()) {
System.out.println("reduce:"+ reduceObj.get());
}*/
// System.out.println(reduceObj);
int reduceObj = integers.parallelStream().reduce(1,(a,b) ->{
if(b%2 == 0) return a*b; else return a;
});
System.out.println(reduceObj);
Spliterator<Integer> spliterator = integers.parallelStream().spliterator();
spliterator.forEachRemaining(n-> System.out.println(n));
对于流api来说,主要就是对集合对操作,因为顶层collection 与方法stream()。
并行流的使用,根据机器是否允许而言。
上面是一个小例子,为了方便使用,建议大家记住自己写的一些样例,比如下面的。
import lombok.Data;
@Data
public class Dish {
private final String name;//菜名
private final boolean vegetarian;//素食标志
private final int calories;//热量
public Dish(String name, boolean vegetarian, int calories) {
this.name = name;
this.vegetarian = vegetarian;
this.calories = calories;
}
}
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class StreamDemo {
public static void main(String[] args) {
//填写案例 多个对象 排序 对比 组装list
List<Dish> dishes = Arrays.asList(
new Dish("jason",true,200),
new Dish("angela", false, 300),
new Dish("huqillang", true, 400),
new Dish("lizhipeng", false, 500)
);
//找到小于400的
List<String> nameList = dishes.stream()
.filter(n -> n.getCalories() < 400)
.sorted(Comparator.comparingInt(Dish::getCalories).reversed())
.map(Dish::getName)
.collect(Collectors.toList());
nameList.stream().forEach(n-> System.out.println(n));
}
}
strea---->中间过程---->结果。这么记忆比较好。
浙公网安备 33010602011771号