day09 lambda和Stream 第一章 Lambda表达式 1.1 函数式编程思想 (注意:不能是抽象类,只能是接口) 而且接口中只能有一个抽象方法
像这样的接口,我们称之为函数式接口,只有基于函数式接口的匿名内部类才能被Lambda表达式简化 。
1.2 Lambda表达式 作用:用于简化匿名内部类代码的书写。
1 2 3 (被重写方法的形参列表) -> { 被重写方法的方法体代码; }
1 2 3 4 public interface A { void abc () ; }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public class LambdaTest1 { public static void main (String[] args) { method(new A () { @Override public void abc () { System.out.println("匿名内部类重写的abc方法执行了..." ); } }); method(()->{ System.out.println("lambda的方式执行了..." ); }); } public static void method (A a) { a.abc(); } }
1.3 Lambda表达式有参数有返回值及省略方式 1 2 3 4 5 6 7 8 9 10 Lambda表达式的省略格式 1. 数据类型可以省略: (Person p) 简化为 (p) (Person p1,Person p2) 简化为 (p1,p2) 2. 如果只有一个参数: ()可以省略 (Person p) 简化为 (p) 再简化为 p 注意: 没有参数,()不能省略 3. 如果{}中只有一句话,那么{}和分号和return ,全部可以省略 注意: 要么全部省略,要么全部保留 4. ->: 永远不能省略
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 public class MyTest03_3 { public static void main (String[] args) { List<Integer> list = new ArrayList <>(); Collections.addAll(list,2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ); list.sort((a,b)->{ return b-a; }); System.out.println(list); Comparator<String> c = (s1, s2)->{ int i = s2.length()-s1.length(); return i == 0 ? s1.compareTo(s2):i; }; TreeSet<String> set1 = new TreeSet <>(c); TreeSet<String> set2 = new TreeSet <>(c); Collections.addAll(set1,"a" ,"c" ,"d" ,"ee" ,"fff" ); Collections.addAll(set2,"aa" ,"ccc" ,"dd" ,"eee" ,"fff" ); System.out.println(set1); System.out.println(set2); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public class LambdaTest2 { public static void main (String[] args) { double [] prices = {99.8 , 128 , 100 }; Arrays.setAll(prices, new IntToDoubleFunction () { @Override public double applyAsDouble (int value) { return prices[value] * 0.8 ; } }); Arrays.setAll(prices, (int value) -> { return prices[value] * 0.8 ; }); System.out.println(Arrays.toString(prices)); Student[] students = new Student [4 ]; students[0 ] = new Student ("蜘蛛精" , 169.5 , 23 ); students[1 ] = new Student ("紫霞" , 163.8 , 26 ); students[2 ] = new Student ("紫霞" , 163.8 , 26 ); students[3 ] = new Student ("至尊宝" , 167.5 , 24 ); Arrays.sort(students, new Comparator <Student>() { @Override public int compare (Student o1, Student o2) { return Double.compare(o1.getHeight(), o2.getHeight()); } }); Arrays.sort(students, (Student o1, Student o2) -> { return Double.compare(o1.getHeight(), o2.getHeight()); }); System.out.println(Arrays.toString(students)); } }
1.4 Lambda表达式的前提
1.5 自定义函数式接口 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 @FunctionalInterface public interface MyFunctionalInter { public abstract void method () ; } public class Demo05LambdaBase { public static void main (String[] args) { fun(new MyFunctionalInter () { @Override public void method () { System.out.println("匿名内部类的方式...." ); } }); fun(()->{ System.out.println("使用lambda表达式的标准格式..." ); }); fun(()-> System.out.println("使用lambda表达式的简化格式" )); } public static void fun (MyFunctionalInter mfi) { mfi.method(); } }
第二章 函数式接口 2.1 Supplier接口的get方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class MyTest02_1 { public static void main (String[] args) { method(new Supplier <Integer>() { @Override public Integer get () { System.out.println("自己规定的生成的逻辑执行了............" ); return 666 ; } }); } public static <T> void method (Supplier<T> sup) { T t = sup.get(); System.out.println("method方法,最终通过 sup对象得到的结果是:" +t); } }
2.2 Consumer接口的accept方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 public class MyTest02_2 { public static void main (String[] args) { method(new Consumer <Object>() { @Override public void accept (Object o) { System.out.println("具体的消费逻辑,执行了,得到的实际数据是:" +o); } },345 ); } public static <T> void method (Consumer<T> con,T t) { con.accept(t); System.out.println("method方法,最终通过 con对象把数据:" +t+"消灭掉了..." ); } }
2.3 Function接口的apply方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 public class MyTest02_3 { public static void main (String[] args) { Integer res = method(new Function <String, Integer>() { public Integer apply (String s) { System.out.println("准备开始转换..." ); return Integer.parseInt(s); } },"123" ); System.out.println("main方法通过method得到的结果是:" +res); } public static <T,R> R method (Function<T,R> fun, T t) { R r = fun.apply(t); System.out.println("method方法,最终通过 fun对象把数据:" +t+"转成了数据" +r); return r; } }
2.4 Predicate的test方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 public class MyTest02_4 { public static void main (String[] args) { boolean res = method(new Predicate <Integer>() { @Override public boolean test (Integer integer) { System.out.println("即将判断" +integer+"是不是偶数!" ); return integer%2 ==0 ; } }, 23 ); System.out.println("main方法通过method得到的结果是:" +res); } public static <T> boolean method (Predicate<T> pre, T t) { Boolean r = pre.test(t); System.out.println("method方法,最终通过 pre对象把数据:" +t+"转成了布尔结果是" +r); return r; } }
第三章 Stream流 3.1 流式思想的介绍
Stream流体验
案例需求:有一个List集合,元素有"张三丰","张无忌","周芷若","赵敏","张强",找出姓张,且是3个字的名字,存入到一个新集合中去。
1 2 3 4 List<String> names = new ArrayList <>(); Collections.addAll(names, "张三丰" ,"张无忌" ,"周芷若" ,"赵敏" ,"张强" ); System.out.println(names);
1 2 3 4 5 6 7 8 9 List<String> list = new ArrayList <>(); for (String name : names) { if (name.startsWith("张" ) && name.length() == 3 ){ list.add(name); } } System.out.println(list);
1 2 List<String> list2 = names.stream().filter(s -> s.startsWith("张" ) && s.length() == 3 ).collect(Collectors.toList()); System.out.println(list2);
3.2 获取Stream流的方式 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 public class Test04_1 { public static void main (String[] args) { List<Integer> list = List.of(2 , 5 , 8 , 3 , 6 , 9 ); Stream<Integer> stream = list.stream(); System.out.println(stream); Map<Integer, Integer> map = Map.of(1 , 11 , 2 , 22 , 3 , 33 ); Set<Map.Entry<Integer, Integer>> set = map.entrySet(); Stream<Map.Entry<Integer, Integer>> stream1 = set.stream(); System.out.println(stream1); String[] arr = {"aa" ,"bb" }; Stream<String> stream2 = Arrays.stream(arr); System.out.println(stream2); Stream<String> a = Stream.of("a" , "b" ); System.out.println(a); } }
常用方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 一、常用中间操作 filter:过滤操作,保留流中符合断言条件的元素,剔除不满足条件的元素。 map:元素映射转换,将流中的每个元素按照指定规则转换为另一个元素,支持同类型 / 跨类型的转换。 flatMap:扁平化映射,将流中每个嵌套的容器元素(如集合、数组)拆分为单个元素,最终合并为一个新的流,解决多层嵌套结构的流处理问题。 sorted:元素排序,无参版本为元素的自然排序,有参版本可传入自定义比较器,实现指定规则的排序。 distinct:元素去重,基于元素的equals()和hashCode()方法,去除流中的重复元素。 limit:流截取,保留流中前 N 个元素,直接截断超出数量的部分。 skip:元素跳过,跳过流中前 N 个元素,仅保留剩余的元素。 peek:遍历消费(调试专用),对流中每个元素执行指定的消费操作,不会改变元素本身,多用于流处理链路的调试。 二、常用终端操作 1. 结果收集类 collect:流结果聚合收集,最核心的终端操作之一,通过传入收集器(通常由Collectors工具类提供),可将流转换为 List、Set、Map 等集合容器,也可实现分组、分区、字符串拼接、统计等复杂聚合操作。 toArray:流转数组,将流中的所有元素转换为对应类型的数组。 2. 遍历消费类 forEach:全量遍历,对流中每个元素执行指定的消费操作,无返回值,串行流下按元素顺序执行,并行流下不保证执行顺序。 forEachOrdered:有序遍历,严格按照流的元素定义顺序执行遍历操作,即使在并行流中也能保证执行顺序与元素顺序一致。 3. 匹配判断类(均为短路求值) anyMatch:任意匹配,判断流中是否存在至少一个符合断言条件的元素,返回布尔值,匹配到第一个符合条件的元素时立即终止计算。 allMatch:全量匹配,判断流中是否所有元素都符合断言条件,返回布尔值,遇到第一个不符合条件的元素时立即终止计算。 noneMatch:无匹配,判断流中是否没有任何元素符合断言条件,返回布尔值,遇到第一个符合条件的元素时立即终止计算。 4. 查找获取类 findFirst:获取首个元素,返回流中第一个元素,结果封装为Optional对象,空流返回空的Optional,有序流中可稳定返回首个元素。 findAny:获取任意元素,返回流中任意一个元素,结果封装为Optional对象,空流返回空的Optional,串行流中多返回首个元素,并行流中用于提升获取效率。 5. 归约聚合类 reduce:归约计算,将流中所有元素按照指定的累加规则,逐步合并为一个最终结果,支持设置初始值,可实现求和、求最值、字符串拼接等各类聚合操作。 6. 基础统计类 count:元素计数,统计并返回流中元素的总个数,返回值为 long 类型。 max:获取最大值,根据传入的比较器规则,返回流中的最大元素,结果封装为Optional对象。 min:获取最小值,根据传入的比较器规则,返回流中的最小元素,结果封装为Optional对象。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 public class Test04_3 { public static void main (String[] args) { List<Integer> list = List.of(2 , 5 ,4 ,10 ,2 ,4 ,12 ,88 ,8 , 3 , 6 , 9 ,2 ,6 ,2 ,0 ,8 ); list.stream() .filter(s->s>2 &&s%2 ==0 ) .distinct() .skip(1 ) .limit(3 ) .forEach(s-> System.out.println(s)); } } public class Test04_4 { public static void main (String[] args) { List<String> list1 = List.of("11" ,"22" ,"333" ,"5" ,"666" ,"22" ); List<String> list2 = List.of("5" ,"6" ,"7" ,"88" ,"999" ,"6" ); Stream<String> stram1 = list1.stream() .filter(s -> s.length() == 2 ); Stream<String> stream2 = list2.stream().filter(s -> s.length() == 1 ); Stream.concat(stram1,stream2) .distinct() .map(s->Integer.parseInt(s)) .sorted((a,b)->b-a) .forEach(s-> System.out.println(s)); Optional<String> max = list1.stream().max((s1, s2) -> Integer.parseInt(s1) - Integer.parseInt(s2)); String s = max.get(); System.out.println(s); } } public class Test04_5 { public static void main (String[] args) { List<String> list1 = List.of("11" ,"22" ,"333" ,"5" ,"666" ,"22" ); long count = list1.stream().filter(s -> s.length() == 2 ).count(); System.out.println(count); System.out.println(list1); } }
3.3 Stream的forEach方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 public class Test04_6 { public static void main (String[] args) { int [] arr = {1 ,3 ,5 }; Arrays.stream(arr).forEach(s-> System.out.println(s)); Stream.of(arr).forEach(s-> System.out.println(s)); String[] arr2 = {"a" ,"b" }; Arrays.stream(arr2).forEach(s-> System.out.println(s)); Stream.of(arr2).forEach(s-> System.out.println(s)); } }
Collection集合的forEach方法
1 2 3 4 5 coll.forEach(s-> System.out.println(s)); } }
Map集合的forEach方法
1 2 3 4 5 map.forEach((key, value) -> System.out.println(key + "==" + value)); } }
3.4 数据收集到 单列集合和双列结合 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 public class Test04_7 { public static void main (String[] args) { List<Integer> list = List.of(2 , 5 , 8 , 3 , 6 , 9 , 1 , 4 , 7 ); List<Integer> list1 = list.stream().filter(s -> s % 2 == 0 ).collect(Collectors.toList()); System.out.println(list1); System.out.println(list); Set<Integer> set = list.stream().filter(s -> s % 2 == 0 ).collect(Collectors.toSet()); System.out.println(set); String[] array = list.stream() .filter(s -> s % 2 == 1 ) .map(s->String.valueOf(s)) .toArray(s->new String [s]); System.out.println(Arrays.toString(array)); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 /* 抽象方法: public abstract <R> Stream<R> map(Function<T, R> mapper) 按照方法参数mapper指定的方式把Stream流对象中的T类型的元素转换成R类型,返回新的Stream流 参数: Function<T, R> mapper: 转换型接口 java.util.function.Function<T, R>接口: 转换型接口 功能: 把T类型的数据转换成R类型 抽象方法: public abstract R apply(T t): 根据方法参数T类型的t,获取R类型的数据 转换前: T类型 转换后: R类型 map: 映射 如果需要将流中的元素映射到另一个流中,可以使用map方法.方法签名 public abstract <R> Stream<R> map(Function<T, R> mapper); 该方法需要一个Function函数式接口参数,可以将当前流中的T类型数据转换为另一种R类型的流. */
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 public class Test04_8 { public static void main (String[] args) { List<String> list = List.of("a,aa" ,"b,bb" ,"c,ccc" ); Map<String, String> map = list.stream() .collect(Collectors.toMap( s -> s.split("," )[0 ], s -> s.split("," )[1 ] )); System.out.println(map); List<Integer> list1 = List.of(2 , 5 , 8 ); Map<Integer, Integer> map1 = list1.stream().collect(Collectors.toMap(s -> s, s -> s * 2 )); System.out.println(map1); } }
3.5 Stream流的练习 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 public class Actor { private String name; @Override public String toString () { return "Actor{" + "name='" + name + '\'' + '}' ; } public String getName () { return name; } public void setName (String name) { this .name = name; } public Actor (String name) { this .name = name; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public class Test { public static void main (String[] args) { List<String> list = List.of("张学友" , "周润发" , "黎明" , "伍佰" , "刘德华" ); List<String> list2 = List.of("杨紫" , "杨敏" , "杨毅杨" , "杨柳" , "鸡柳" ); Stream<String> stream = list.stream() .filter(s -> s.length() == 3 ) .limit(2 ); Stream<String> stream1 = list2.stream() .filter(s -> s.startsWith("杨" )) .skip(1 ); Map<String, Actor> map = Stream.concat(stream, stream1).map(s -> new Actor (s)).collect(Collectors.toMap(s -> s.getName(), s -> s)); System.out.println(map); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 1. Stream.concat(stream, stream1) —— 合并流作用:把两个流 “拼” 在一起,变成一个大流。 结果: 新的大流里的数据顺序是:["张学友" , "周润发" , "杨敏" , "杨毅杨" , "杨柳" ]。 2. .map(s -> new Actor (s)) —— 映射(转型)流里现在是 String(字符串名字)。 s 代表当前的名字(例如第一个 s 是 "张学友" )。 new Actor (s):调用 Actor 的构造方法,把这个名字传进去,造一个新的 Actor 对象。结果: 流变成了 Stream<Actor>。 里面装的是 5 个对象:[Actor对象(张学友), Actor对象(周润发), ...]。 3. .collect(Collectors.toMap(s -> s.getName(), s -> s)) —— 收集到 Map第一个参数 s -> s.getName() (Key 的规则): s:现在代表流里的 Actor 对象。 s.getName():调用 Actor 的 getName() 方法,**拿到名字字符串。** 第二个参数 s -> s (Value 的规则): s:还是那个 Actor 对象。 s:直接返回它自己。 含义:Map 的 Value 就存这个对象本身。
第四章 方法引用 例子 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 public class MyTools { public static boolean isEven (int a) { System.out.println("自定义的类中.......判断是不是偶数:" +a); return a%2 ==0 ; } public boolean isOdd (int a) { System.out.println("自定义的类中.......判断是不是奇数:" +a); return a%2 ==1 ; } } public class MtTest02 { public static void main (String[] args) { List<Integer> list = List.of(1 , 3 , 5 , 7 , 2 , 5 , 7 , 8 , 4 ); ArrayList<Integer> list1 = new ArrayList <>(list); MyTools tools = new MyTools (); list1.removeIf(tools::isOdd); System.out.println(list1); } }
4.1 输出语句的方法引用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 @FunctionalInterface public interface MyPrinter { public abstract void printLine (String str) ; } public class Demo04MethodRef { public static void main (String[] args) { String str = "hello world" ; show(str, new MyPrinter () { @Override public void printLine (String str) { System.out.println(str); } }); show(str,(String s)->{ System.out.println(s); }); show(str,s-> System.out.println(s)); show(str,System.out::println); } public static void show (String ss,MyPrinter mp) { mp.printLine(ss); } }
4.2 对象名的方法引用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 public class Assistant { public void buyComputer (Integer money) { System.out.println("很高兴为您买到价值为: " +money+" 元的一台电脑" ); } } public class Demo05MethodRef { public static void main (String[] args) { int money = 10000 ; Assistant as = new Assistant (); show(money, new Consumer <Integer>() { @Override public void accept (Integer num) { as.buyComputer(num); } }); show(money,(Integer num)->{ as.buyComputer(num); }); show(money,as::buyComputer); } public static void show (Integer money,Consumer<Integer> con) { con.accept(money); } }
4.3 类名引用静态方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 public class Assistant { public static void buyComputer (Integer money) { System.out.println("很高兴为您买到价值为: " +money+" 元的一台电脑" ); } } public class Demo06MethodRef { public static void main (String[] args) { int num = 10000 ; show(num, new Consumer <Integer>() { @Override public void accept (Integer n) { Assistant.buyComputer(n); } }); show(num,(Integer n)->{ Assistant.buyComputer(n); }); show(num,Assistant::buyComputer); } public static void show (Integer i,Consumer<Integer> con) { con.accept(i); } }
4.4 类名引用静态方法练习 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 public class Demo07MethodRefTest { public static void main (String[] args) { String str = "1235" ; show(str, new Function <String, Integer>() { @Override public Integer apply (String s) { return Integer.parseInt(s); } }); show(str,(String s)->{return Integer.parseInt(s);}); show(str,Integer::parseInt); } public static void show (String strNum,Function<String,Integer> fun) { Integer num = fun.apply(strNum); System.out.println(num); } }
4.5 类名引用构造方法 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 public class Person { private String name; } public class Demo07ConstructorRef { public static void main (String[] args) { String name = "张三" ; show(name, new Function <String, Person>() { @Override public Person apply (String s) { return new Person (s); } }); show(name,(String n)->{return new Person (n);}); show(name,Person::new ); } public static void show (String name,Function<String,Person> fun) { Person p = fun.apply(name); System.out.println(p); } }
4.6 数组的构造引用 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 public class Demo08ArrayMethodRef { public static void main (String[] args) { int len = 5 ; show(len, new Function <Integer, int []>() { @Override public int [] apply(Integer num) { int [] arr = new int [num]; for (int i = 0 ; i < arr.length; i++) { arr[i] = i*10 ; } return arr; } }); show(len,(Integer num)->{return new int [num];}); show(len,int []::new ); } public static void show (Integer num,Function<Integer, int []> fun) { int [] arr = fun.apply(num); System.out.println("数组长度: " +arr.length); } }
作业 1 2 3 4 public enum MyStatus { DAI,YI,FA,OVER,CANCEL }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 public class Order { private String oid; private String uid; private double money; private MyStatus status; @Override public boolean equals (Object o) { if (this == o) return true ; if (o == null || getClass() != o.getClass()) return false ; Order order = (Order) o; if (Double.compare(money, order.money) != 0 ) return false ; if (!Objects.equals(oid, order.oid)) return false ; if (!Objects.equals(uid, order.uid)) return false ; return status == order.status; } @Override public int hashCode () { int result; long temp; result = oid != null ? oid.hashCode() : 0 ; result = 31 * result + (uid != null ? uid.hashCode() : 0 ); temp = Double.doubleToLongBits(money); result = 31 * result + (int ) (temp ^ (temp >>> 32 )); result = 31 * result + (status != null ? status.hashCode() : 0 ); return result; } @Override public String toString () { return "Order{" + "oid='" + oid + '\'' + ", uid='" + uid + '\'' + ", money=" + money + ", status=" + status + '}' ; } ... public Order (String oid, String uid, double money, MyStatus status) { this .oid = oid; this .uid = uid; this .money = money; this .status = status; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 public class User { private String uid; private String name; private int level; @Override public boolean equals (Object o) { if (this == o) return true ; if (o == null || getClass() != o.getClass()) return false ; User user = (User) o; if (level != user.level) return false ; if (!Objects.equals(uid, user.uid)) return false ; return Objects.equals(name, user.name); } @Override public int hashCode () { int result = uid != null ? uid.hashCode() : 0 ; result = 31 * result + (name != null ? name.hashCode() : 0 ); result = 31 * result + level; return result; } @Override public String toString () { return "User{" + "uid='" + uid + '\'' + ", name='" + name + '\'' + ", level=" + level + '}' ; } ... public User (String uid, String name, int level) { this .uid = uid; this .name = name; this .level = level; } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 public class OrderProcessor { private List<Order> orderList = new ArrayList <>(); private Map<String,User> map = new HashMap <>(); public OrderProcessor () { orderList.add(new Order ("001" ,"u01" ,100 ,MyStatus.DAI)); orderList.add(new Order ("002" ,"u01" ,200 ,MyStatus.FA)); orderList.add(new Order ("003" ,"u01" ,300 ,MyStatus.YI)); orderList.add(new Order ("004" ,"u02" ,400 ,MyStatus.OVER)); orderList.add(new Order ("005" ,"u02" ,500 ,MyStatus.CANCEL)); orderList.add(new Order ("006" ,"u01" ,600 ,MyStatus.YI)); orderList.add(new Order ("007" ,"u01" ,700 ,MyStatus.DAI)); map.put("u01" ,new User ("u02" ,"迪丽热巴" ,5 )); map.put("u02" ,new User ("u02" ,"杨幂" ,3 )); } public void showYi () { orderList.stream().filter(order -> order.getStatus() == MyStatus.YI).forEach(s-> { User user = map.get(s.getUid()); System.out.println(user+"===>" +s); }); } public void showPayMoney () { double sum = orderList.stream().filter(order -> order.getStatus() == MyStatus.YI).mapToDouble(s -> s.getMoney()).sum(); System.out.println("已经支付的订单总金额是:" +sum); } public void showByPrice () { orderList.stream().sorted((a,b)->Double.compare(b.getMoney(),a.getMoney())).forEach(System.out::println); } public void showTop3 () { orderList.stream().sorted((a,b)->Double.compare(b.getMoney(),a.getMoney())).limit(3 ).forEach(System.out::println); } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public class TestAPP { public static void main (String[] args) { OrderProcessor app = new OrderProcessor (); app.showYi(); app.showPayMoney(); app.showByPrice(); System.out.println("-----------------" ); app.showTop3(); } }