Lamda
package com.tenpay.risk.aml.cdd.batch.apisvr.core.basic; import lombok.*; import lombok.experimental.Accessors; import org.junit.Before; import org.junit.BeforeClass; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import rx.functions.Action; import java.text.Collator; import java.util.*; import java.util.Arrays; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.Stream; public class LamdaTest { private List<String> strings; private List<Integer> ints; private List<String> names; private List<Student> students; // 数据准备,在执行测试方法之前先初始化数据,Junit版本过高使用@BeforeEach替代@Before @BeforeEach public void init() { strings = Arrays.asList("abc", "0", "bc", "for","bc", "e fg", "jse", "Ff", "jkl","886"); ints = Arrays.asList(100,84,66,5,41,2,0,-7,88,-201); names = Arrays.asList("张三","李四","王二","麻子","翠花","壮壮","狗蛋","小红"); students = new ArrayList<>(); students.add(new Student(1,"米大傻",18,90)); students.add(new Student(2,"米二傻",18,91)); students.add(new Student(3,"米三傻",19,92)); students.add(new Student(4,"米四傻",18,null)); students.add(new Student(5,"米五傻",20,88)); students.add(new Student(6,"米六傻",18,98)); students.add(new Student(7,"米七傻",21,100)); students.add(new Student(8,"米七傻",21,100)); students.add(new Student(9,"米九傻",19,73)); students.add(new Student(10,"米十傻",22,90)); } @Test void testForeach() { strings.forEach(System.out::println); students.forEach(System.out::println); } /** * Collectors将集合转换成list,set,map */ @Test void testCollect() { //toSet Set<String> collect = strings.stream().collect(Collectors.toSet()); System.out.print("set:"+collect); System.out.println(); //toList List<Integer> collect1 = ints.stream().collect(Collectors.toList()); System.out.print("list:"+collect1); System.out.println(); //toMap Map<String, String> collect2 = strings.stream().distinct().collect(Collectors.toMap(p -> "V_" + p, q -> q)); for (Map.Entry<String, String> stringStringEntry : collect2.entrySet()) { System.out.println(stringStringEntry.getKey()+":"+stringStringEntry.getValue()); } Map<String, Student> collect3 = students.stream().collect(Collectors.toMap(x -> x.getId().toString(), e -> e)); for (Map.Entry<String, Student> stringStudentEntry : collect3.entrySet()) { System.out.println(stringStudentEntry.getKey()+":"+stringStudentEntry.getValue()); } //group Map<Integer, List<Student>> collect4 = students.stream().collect(Collectors.groupingBy(x -> x.getAge())); System.out.println(collect4); } @Test void testFilter() { List<String> f = strings.stream().filter(p -> p.contains("f")).collect(Collectors.toList()); System.out.println(f); List<Student> collect = students.stream().filter(p -> p.getAge() >= 15).collect(Collectors.toList()); System.out.println(collect); } @Test void testLimitSkip() { List<Integer> collect = ints.stream().skip(2).limit(5).collect(Collectors.toList()); System.out.println(collect); //66,5,41,2,0 } @Test void testMap() { String collect = students.stream().map(Student::getName).collect(Collectors.joining(",")); System.out.println(collect); } @Test void testSorted() { List<Integer> collect = ints.stream().sorted().collect(Collectors.toList()); System.out.println(collect); //正向按照中文排序 List<String> collatorNames = names.stream().sorted(Collator.getInstance(Locale.CHINA)).collect(Collectors.toList()); System.out.println("collatorNames = " + collatorNames); // 反向按中文排序 List<String> reverseOrderNames = names.stream().sorted(Collections.reverseOrder(Collator.getInstance(Locale.CHINA))).collect(Collectors.toList()); System.out.println("reverseOrderNames = " + reverseOrderNames); List<Student> collectStudents = students.stream().sorted(Comparator.comparing(Student::getAge).thenComparing(Student::getId)) .collect(Collectors.toList()); collectStudents.forEach(System.out::println); } @Test void testExists() { //任意匹配 boolean b = students.stream().anyMatch(p -> p.getScore() >= 80); System.out.println(b); //所有匹配 boolean b1 = ints.stream().allMatch(p -> p > 0); System.out.println(b1); //都没匹配 boolean b2 = ints.stream().noneMatch(p -> p < 0); System.out.println(b2); } @Test void testReduce() { Optional<Integer> reduce1 = students.stream().map(p -> p.getScore() ==null ? 0 : p.getScore()).reduce(Integer::sum); reduce1.ifPresent(System.out::println); } @Test void test(){ ArrayList<Student> students = new ArrayList<>(); students.add(new Student(1,"binfire",30,100)); students.add(new Student(2,"shanshan",15,60)); students.add(new Student(3,"binfire1",15,30)); //foreach students.forEach(System.out::println); //collect: 收集器,将流转换成 list set map List<Student> collect1 = students.stream().collect(Collectors.toList()); Set<Student> collect2 = students.stream().collect(Collectors.toSet()); Map<String, Student> collect3 = students.stream().collect(Collectors.toMap(Student::getName, x -> x)); Map<String, Student> collect4 = students.stream().collect(Collectors.toMap(Student::getName, x -> x,(oldValue,newValue)->newValue)); //按照Name分组,如果有新值则取代新值 Map<String, Student> collect6 = students.stream().collect(Collectors.toMap(x -> "F"+x.getName(), y -> y)); Map<Integer, List<Student>> collect5 = students.stream().collect(Collectors.groupingBy(p -> p.getAge())); for (Map.Entry<String, Student> stringStudentEntry : collect3.entrySet()) { System.out.println(stringStudentEntry.getKey()+":"+stringStudentEntry.getValue()); } //map,映射每个元素对应的结果 String str = students.stream().filter(p -> p.name.startsWith("binfire")).map(Student::getName).collect(Collectors.joining(",")); System.out.println(str); //skip,limit List<Student> collect8 = students.stream().skip(2).limit(5).collect(Collectors.toList()); //判断是否存在 boolean exists = students.stream().anyMatch(p -> p.name.equals("binfire")); Optional<Student> binfire = students.stream().filter(p -> p.name.equals("binfire")).findFirst(); binfire.ifPresent(p->{ System.out.println(p); }); if(binfire.isPresent()){ Student student = binfire.get(); System.out.println(student); } //map Map<String, Student> collect = students.stream().collect(Collectors.toMap(Student::getName, x -> x)); for (Map.Entry<String, Student> stringStudentEntry : collect.entrySet()) { System.out.println("key="+stringStudentEntry.getKey()+";value="+stringStudentEntry.getValue()); } //Func String s = testFunction(LamdaTest::getResult, "123"); System.out.println(s); testAction(LamdaTest::testPrint,"123"); run(new Consumer<Void>() { @Override public void accept(Void unused) { System.out.println("fff"); } }); } @Test void testThread() { new Thread(()-> System.out.println("fff")).start(); new Thread(new Runnable() { @Override public void run() { System.out.println("zzz"); } }).start(); List<String> strings = Arrays.asList("java", "javascript", "python"); Collections.sort(strings, new Comparator<String>() { @Override public int compare(String o1, String o2) { return o1.length()-o2.length(); } }); Collections.sort(strings,(a,b)->a.length()-b.length()); } /** * Func * @param func * @param args * @return */ String testFunction(Function<String,String> func,String args){ String apply = func.apply(args); return apply; } void run(Consumer<Void> action){ long startTime=System.currentTimeMillis(); action.accept(null); long endTime=System.currentTimeMillis(); System.out.println("used time:"+(endTime-startTime)); } /* public void ifPresent(Consumer<? super T> consumer) { if (value != null) consumer.accept(value); } *//** * If a value is present, and the value matches the given predicate, * return an {@code Optional} describing the value, otherwise return an * empty {@code Optional}. * * @param predicate a predicate to apply to the value, if present * @return an {@code Optional} describing the value of this {@code Optional} * if a value is present and the value matches the given predicate, * otherwise an empty {@code Optional} * @throws NullPointerException if the predicate is null *//* public Optional<T> filter(Predicate<? super T> predicate) { Objects.requireNonNull(predicate); if (!isPresent()) return this; else return predicate.test(value) ? this : empty(); } *//** * If a value is present, apply the provided mapping function to it, * and if the result is non-null, return an {@code Optional} describing the * result. Otherwise return an empty {@code Optional}. * * @apiNote This method supports post-processing on optional values, without * the need to explicitly check for a return status. For example, the * following code traverses a stream of file names, selects one that has * not yet been processed, and then opens that file, returning an * {@code Optional<FileInputStream>}: * * <pre>{@code * Optional<FileInputStream> fis = * names.stream().filter(name -> !isProcessedYet(name)) * .findFirst() * .map(name -> new FileInputStream(name)); * }</pre> * * Here, {@code findFirst} returns an {@code Optional<String>}, and then * {@code map} returns an {@code Optional<FileInputStream>} for the desired * file if one exists. * * @param <U> The type of the result of the mapping function * @param mapper a mapping function to apply to the value, if present * @return an {@code Optional} describing the result of applying a mapping * function to the value of this {@code Optional}, if a value is present, * otherwise an empty {@code Optional} * @throws NullPointerException if the mapping function is null *//* public<U> Optional<U> map(Function<? super T, ? extends U> mapper) { Objects.requireNonNull(mapper); if (!isPresent()) return empty(); else { return Optional.ofNullable(mapper.apply(value)); } } */ /** * Action * @param action * @param args */ void testAction(Consumer<String> action,String args){ action.accept(args); } public static void testPrint(String a){ System.out.println(a); } public static String getResult(String a){ return a; } @Data @AllArgsConstructor @NoArgsConstructor @Accessors(chain = true) @ToString class Student { private Integer id; private String name; private Integer age; private Integer score; } @Test void testLamda() { ILamdaTest lamdaTest=(a,b)-> {return a+b;}; int func = lamdaTest.func(1, 2); System.out.println(func); } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix