Java8中stream流处理数据21个小案例(学习使用)
1、首先准备两个类(苹果类,可以一个苹果颜色的枚举)
public class Apple {
// 名字
private String name;
// 重量
private double weight;
// 颜色(枚举类)
private Color color;
// 城市
private String nation;
public Apple() {
}
@Override
public String toString() {
return "Apple{" +
"name='" + name + '\'' +
", weight=" + weight +
", color=" + color +
", nation='" + nation + '\'' +
'}';
}
@Override
public int hashCode() {
return Objects.hash(name, weight, color, nation);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public Color getColor() {
return color;
}
public void setColor(Color color) {
this.color = color;
}
public String getNation() {
return nation;
}
public void setNation(String nation) {
this.nation = nation;
}
public Apple(String name, double weight, Color color, String nation) {
this.name = name;
this.weight = weight;
this.color = color;
this.nation = nation;
}
}
public enum Color {
/**
* 红色,绿色,蓝色
*/
RED("红色"),GREEN("绿色"),Blue("蓝色");
private final String co;
Color(String co) {
this.co = co;
}
public String getCo() {
return co;
}
}
2、向集合中加入数据,开始处理list集合
Apple apple1 = new Apple("Apple1", 32.23, Color.RED, "china");
Apple apple2 = new Apple("Apple2", 23, Color.RED, "japan");
Apple apple3 = new Apple("Apple3", 12.09, Color.GREEN, "america");
Apple apple4 = new Apple("Apple4", 43.12, Color.Blue, "english");
Apple apple5 = new Apple("Apple5", 12.09, Color.GREEN, "oss");
Apple apple6 = new Apple("Apple6", 12.09, Color.GREEN, "fsd");
Apple apple7 = new Apple("Apple7", 12.09, Color.Blue, "fa");
Apple apple8 = new Apple("Apple8", 12.09, Color.Blue, "as");
Apple apple9 = new Apple("Apple9", 10.232, Color.GREEN, "sfs");
Apple apple10 = new Apple("Apple10", 43.22, Color.RED, "zz");
List<Apple> appleList = Arrays.asList(apple1, apple2, apple3, apple4, apple5, apple6, apple7, apple8, apple9, apple10);
案例1:按照重量排序,重量一样时候按照城市排序
list.sort(Comparator.comparing(Apple::getWeight).thenComparing(Apple::getNation));
案例2:筛选要么是重量大于23的红苹果,要么是绿苹果的集合
// 方式一
Predicate<Apple> predicate = apple -> Color.RED.equals(apple.getColor());
list.stream().filter(predicate.and(a -> a.getWeight() > 23).or(b -> b.getColor().equals(Color.GREEN))).forEach(System.out::println);
// 方式二
list.stream().filter(apple -> Color.RED.equals(apple.getColor()) && apple.getWeight() > 23 || Color.GREEN.equals(apple.getColor())).forEach(System.out::println);
案例3:挑选重量小于30的苹果,然后按照城市名字排序,并把名字打印出来
list.stream().filter(apple -> apple.getWeight() < 30).map(Apple::getNation).sorted().forEach(System.out::println);
案例4:筛选前二个红苹果
appleList.stream().filter(apple -> Color.RED.equals(apple.getColor())).limit(2).forEach(System.out::println);
案例5:筛选除了前两个的其他所有红苹果
appleList.stream().filter(apple -> Color.RED.equals(apple.getColor())).skip(2).forEach(System.out::println);
案例6:遍历所有每个苹果所在城市名字的长度
appleList.stream().map(apple -> apple.getNation().length()).forEach(System.out::println);
案例7:找到任意一个红苹果(第一个、是否全是红,是否有一个红色,是否没有红)
// 任意一个红苹果
appleList.stream().filter(apple -> Color.RED.equals(apple.getColor())).findAny().ifPresent(System.out::println);
// 第一个红苹果
Optional<Apple> first = appleList.stream().filter(apple -> Color.RED.equals(apple.getColor())).findFirst();
System.out.println(first.orElse(new Apple("11", 23, Color.RED, "lalalla")));
// 是否全是红
System.out.println(appleList.stream().allMatch(apple -> Color.RED.equals(apple.getColor())));
// 是否有红
System.out.println(appleList.stream().anyMatch(apple -> Color.RED.equals(apple.getColor())));
// 是否没有红
System.out.println(appleList.stream().noneMatch(apple -> Color.RED.equals(apple.getColor())));
案例8:计算所有苹果的重量和
// 方式一
System.out.println(appleList.stream().mapToDouble(Apple::getWeight).reduce(0.00, (a, b) ->
// 为了防止小数位过多
new BigDecimal(Double.toString(a)).add(new BigDecimal(Double.toString(b))).doubleValue()
));
// 方式二
System.out.println(appleList.stream().mapToDouble(Apple::getWeight).sum());
案例9:找出最重的苹果
// 方式一
appleList.stream().map(Apple::getWeight).reduce(Double::max).ifPresent(System.out::println);
// 方式二
appleList.stream().max(Comparator.comparingDouble(Apple::getWeight)).ifPresent(apple -> System.out.println(apple.getWeight()));
// 方式三
appleList.stream().mapToDouble(Apple::getWeight).max().ifPresent(System.out::println);
案例10:返回所有的城市名字字符串,按照城市名字排序
System.out.println(appleList.stream().map(Apple::getNation)
.distinct()
.sorted()
// 效率不高
//.reduce("", (a, b) -> a + b));
.collect(Collectors.joining(",")));
案例11:求出平均重量
// 方式一
appleList.stream().mapToDouble(Apple::getWeight).average().ifPresent(System.out::println);
// 方式二
System.out.println(appleList.stream().collect(Collectors.averagingDouble(Apple::getWeight)));
案例12:按照苹果颜色分组,颜色一样按照重量分组
Map<Color, Map<Double, List<Apple>>> collect = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.groupingBy(Apple::getWeight)));
案例13:按照颜色分组,并且显示每种颜色分组后的数量
Map<Color, Long> collect = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.counting()));
collect.entrySet().forEach(System.out::println);
// 补充,假如挑选所要结果后大于3的
collect.entrySet().stream().filter(colorLongEntry -> colorLongEntry.getValue() > 3).forEach(System.out::println);
案例14:按颜色分组,挑选出每个分组中重量最大的,重量一样的话,根据城市名字
Map<Color, Optional<Apple>> collect = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.maxBy(Comparator.comparingDouble(Apple::getWeight).thenComparing(Apple::getNation))));
// 去掉optional
Map<Color, Apple> collect1 = collect.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, colorOptionalEntry -> colorOptionalEntry.getValue().orElse(new Apple()), (a, b) -> a));
System.out.println(collect1);
// 方式二
//Map<Color, Apple> collect3 = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingDouble(Apple::getWeight).thenComparing(Apple::getNation)), Optional::get)));
Map<Color, Apple> collect2 = appleList.stream().collect(Collectors.toMap(Apple::getColor, Function.identity(), BinaryOperator.maxBy(Comparator.comparingDouble(Apple::getWeight).thenComparing((Apple::getNation)))));
System.out.println("-----------------------------");
System.out.println(collect2);
案例15:同时找出苹果的总数量,最大值,最小值,平均值
DoubleSummaryStatistics collect = appleList.stream().collect(Collectors.summarizingDouble(Apple::getWeight));
System.out.println(collect);
案例16:按照颜色分组,找出每个分组下的最大值,总数。最小值,平均值
Map<Color, DoubleSummaryStatistics> collect1 = appleList.stream().collect(Collectors.groupingBy(Apple::getColor, Collectors.summarizingDouble(Apple::getWeight)));
collect1.entrySet().forEach(System.out::println);
案例17:重量大于20的分为一组,重量小于20的分为一组
// 方式一
Map<Boolean, List<Apple>> collect = appleList.stream().collect(Collectors.groupingBy(a -> a.getWeight() > 20));
collect.forEach((aBoolean, apples) -> System.out.println(aBoolean + apples.toString()));
// 方式二
Map<Boolean, List<Apple>> collect1 = appleList.stream().collect(Collectors.partitioningBy(apple -> apple.getWeight() > 20));
collect1.forEach((aBoolean, apples) -> System.out.println(aBoolean + apples.toString()));
案例18:基于案例17,每种分组再按照颜色分组
Map<Boolean, Map<Color, List<Apple>>> collect = appleList.stream().collect(Collectors.partitioningBy(apple -> apple.getWeight() > 20, Collectors.groupingBy(Apple::getColor)));
System.out.println(collect);
案例19:重量大于20的分为一组,重量小于20的分为一组,只要分组的重量最大的
Map<Boolean, Apple> collect = appleList.stream().collect(Collectors.partitioningBy(apple -> apple.getWeight() > 20, Collectors.collectingAndThen(Collectors.maxBy(Comparator.comparingDouble(Apple::getWeight)), Optional::get)));
案例20:按照重量大于20的一组,小于20的一组,找出每组个数
Map<Boolean, Long> collect = appleList.stream().collect(Collectors.partitioningBy(apple -> apple.getWeight() > 20, Collectors.counting()));
案例21:先根据重量是否大于20分组,再根据颜色是否为红色分组
Map<Boolean, Map<Boolean, List<Apple>>> collect = appleList.stream().collect(Collectors.partitioningBy(apple -> apple.getWeight() > 20, Collectors.partitioningBy(apple -> apple.getColor().equals(Color.RED))));
扩充知识:
public static void main(String[] args) {
// 生成1-100的偶数流
//test1();
// 生成1-100内的勾股数
//test2();
// iterate打印10个偶数
//test3();
// 生成10个斐波那契数列
//test4();
//生成随机数或者全是1的无限流
//test5();
}
public static void test1(){
// 打印个数(注意,rangeClosed包括两端,range不包括右端点)
IntStream.rangeClosed(1, 100).filter(value -> value % 2 == 0).forEach(System.out::println);
}
public static void test2(){
IntStream.rangeClosed(1,100).boxed().flatMap(
a->IntStream.rangeClosed(a,100).mapToObj(b->new double[]{a,b,Math.sqrt(a*a+b*b)})
).filter(t->t[2]%1==0).forEach(result->System.out.println(result[0]+""+result[1]+result[2]));
}
public static void test3(){
Stream.iterate(0,a->a+2).limit(10).forEach(System.out::println);
}
public static void test4(){
Stream.iterate(new int[]{0,1},a->new int[]{a[1],a[0]+a[1]}).limit(10).forEach(result-> System.out.println(result[0]));
}
public static void test5(){
// 生成随机数
Stream.generate(Math::random).limit(20).forEach(System.out::println);
// 生成全是1的无限流
Stream.generate(()->1).limit(20).forEach(System.out::println);
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!