Java之Lambda使用

Stream接口中的常见方法
| List<Integer> nums =Arrays.asList(1,1,null,2,3,4,null,5,6,7,8,9,10); |
| System.out.println("sum is:"+nums.stream() |
| .filter(num -> num != null) |
| .distinct() |
| .mapToInt(num -> num * 2) |
| .peek(System.out::println) |
| .skip(2) |
| .limit(4) |
| .sum()); |
| |
| |
| 结果: |
| 2 |
| 4 |
| 6 |
| 8 |
| 10 |
| 12 |
| sum is:36 |
流操作
1.Java中filter和removeIf.
- 介绍
- 区别:
- filter过滤, 会把符合的留下来.
- removeIf过滤之后, 会把相同的干掉.
- 示例
| List<Student> stuList = new ArrayList<>(); |
| Collections.addAll(stuList, |
| new Student(1, "张三"), |
| new Student(2, "李四"), |
| new Student(3, "王老五") |
| ); |
| |
| |
| List<Student> filterList = stuList.stream().filter(student -> { |
| Integer valueOf = Integer.valueOf("1"); |
| return !valueOf.equals(student.getStuId()); |
| }).collect(Collectors.toList()); |
| |
| |
| boolean removeIf = filterList.removeIf(student -> { |
| Integer valueOf = Integer.valueOf("3"); |
| return valueOf.equals(student.getStuId()); |
| }); |
| |
| |
| filterList.forEach(System.out::println); |
| |
| |
| stuList.stream().filter(stu02List::contains).collect(Collectors.toList()); |
| |
| |
| List<User> resultList = createList().stream() |
| .filter(o->!newList.contains(o)).collect(Collectors.toList()); |
2.Java中forEach使用.
- 介绍
- 示例
| |
| list.stream().forEach(v -> System.err.println(v.getName()+","+v.getSex())); |
| |
| |
| map.forEach((key, value) -> System.out.println("key:" + key + "; value" + JSON.toJSON(value))); |
3.Java中Peek使用.
- 介绍
- peek 方法很简单,我们在 peek 方法里面做任意没有返回值的事情,比如打印日志.
- 与forEach()方法效果类似,但该方法会返回一个新的流,而forEach()无返回
- 示例
| |
| public void testPeek() { |
| List<String> list = new ArrayList<String>() {{ |
| add("1"); |
| add("2"); |
| add("3"); |
| }}; |
| list.stream().map(s -> Integer.valueOf(s)) |
| .peek(s -> System.out.println(s)) |
| .collect(Collectors.toList()); |
| } |
| |
| |
| wordVoList.stream().peek(aItem - > { |
| List<String> strList = xxxMapper.findAll(); |
| aItem.setstuList(strList); |
| } |
| ).collect(collectors.toList()); |
| |
| |
| .stream().peek(xxxServiceImpl::accept).collect(collectors.toList()); |
| |
| private static void accept(ExperienceVO aItem) { |
| if (不等于空) { |
| aItem.setCaseStatusFlag(ExperienceEnum.getValue(aItem.CaseStatus())); |
| } |
| } |
4.Java中Map使用.
- 介绍
- map 方法可以让我们进行一些流的转化,比如原来流中的元素是 A,通过 map 操作,可以使返回的流中的元素是 B.
- 实例
| |
| public void testMap() { |
| List<String> list = new ArrayList<String>() {{ |
| add("1"); |
| add("2"); |
| add("3"); |
| }}; |
| List<String> strLowerList = list.stream() |
| .map(str -> str.toLowerCase()) |
| .collect(Collectors.toList()); |
| } |
| |
| |
| List<Integer> listPlus = list.stream().map(value -> value.getId()).collect(Collectors.toList()); |
| List<Integer> listPlus = list.stream().map(Student::getId).collect(Collectors.toList()); |
| |
| |
| private static List<LocationVo> convert2LocationVo(List<LocationDto> locationDtoList) { |
| if (null == locationDtoList) { |
| return null; |
| } |
| return locationDtoList.stream().map(item -> { |
| LocationVo locationVo = new LocationVo(); |
| locationVo.setUpdateBy(item.getUpdateBy()); |
| locationVo.setUpdateDate(item.getUpdateDate()); |
| locationVo.setVersion(item.getVersion()); |
| return locationVo; |
| }).collect(Collectors.toList()); |
| } |
| |
| |
| |
| private List<StudentPlus> obj(List<Student> stuList) { |
| return stuList.stream().map(this::conversion).collect(Collectors.toList()); |
| } |
| |
| |
| private StudentPlus conversion(Student stu) { |
| StudentPlus studentPlus = new StudentPlus(); |
| studentPlus.setId(stu.getId()); |
| studentPlus.setName(stu.getName()); |
| studentPlus.setDate(new Date(stu.getDate())); |
| return studentPlus; |
| } |
| |
| |
| List<Map<String,Object>> personToMap = peopleList.stream().map((p) -> { |
| Map<String, Object> map = new HashMap<>(); |
| map.put("is", p.getId()); |
| map.put("age", p.getAge()); |
| return map; |
| }).collect(Collectors.toList()); |
5.Java中MapTo...使用.
- 介绍
- mapToInt 方法的功能和 map 方法一样,只不过 mapToInt 返回的结果已经没有泛型,已经明确是 int 类型的流了,源码如下:
- 实例
| public void testMapToInt () { |
| List<String> list = new ArrayList<String>() {{ |
| add("1"); |
| add("2"); |
| add("3"); |
| }}; |
| List<Integer> collect = list.stream() |
| .mapToInt(s -> Integer.valueOf(s)) |
| |
| |
| |
| .mapToObj(s -> s) |
| .collect(Collectors.toList()); |
| double sum = list.stream() |
| .mapToDouble(s -> Double.valueOf(s)) |
| |
| .sum(); |
| |
| } |
6.Java中Distinct使用.
- 介绍
- distinct 方法有去重的功能
- 可在.map()、.stream()关键字之后使用.
- 实例
| public void testDistinct(){ |
| List<String> list = new ArrayList<String>() {{ |
| add("1"); |
| add("2"); |
| add("2"); |
| }}; |
| list.stream() |
| .map(s -> Integer.valueOf(s)) |
| .distinct() |
| .collect(Collectors.toList()); |
| } |
7.Java中Sorted使用.
- 介绍
- Sorted 方法提供了排序的功能,并且允许我们自定义排序
- 实例
| public void testSorted() { |
| List<String> list = new ArrayList<String>() {{ |
| add("1"); |
| add("2"); |
| add("3"); |
| }}; |
| list.stream() |
| .map(s -> Integer.valueOf(s)) |
| |
| .sorted() |
| .collect(Collectors.toList()); |
| |
| list.stream() |
| .map(s -> Integer.valueOf(s)) |
| |
| .sorted(Comparator.reverseOrder()) |
| .collect(Collectors.toList()); |
| } |
| |
| |
| .sorted(Comparator.comparing(ResourceFeverRankingVO::getDateSoft).reversed()) |
| .collect(Collectors.toList()); |
| |
| |
| studentList.stream().sorted(Comparator.comparing(StudentInfo::getAge)).collect(Collectors.toList()) |
8.Java中skip使用.
- 介绍
- 实例
| List<String> list = new ArrayList<>(); |
| Collections.addAll(list, "张三", "李四", "王老五", "潘丽平"); |
| System.out.println(list.stream().skip(2).collect(Collectors.toList())); |
| |
9.Java中flatMap使用.
- 介绍
- Lambda中Map是对流元素进行转换,flatMap 是对流中的元素(集合)进行平铺后合并,即对流中的每个元素平铺后又转换成为了 Stream 流。
- flatMap 首先将一个函数应用于元素,然后将其展平,当你需要将 [[a,b,c],[d,e,f],[x,y,z]] 具有两个级别的数据结构转换为 [a,b,c,d,e,f,x,y,z] 这样单层的数据结构时,就选择使用 flatMap 处理。
- 如果是 [a,b,c,d,e,f,x,y,z] 转换为大写 [A,B,C,D,E,F,X,Y,Z] 这样单层转换,就使用 map 即可。
- 示例
| |
| |
| List<String> dataList = Lists.newArrayList("hello", "world"); |
| List<String> transform = dataList.stream() |
| .flatMap( |
| data -> Arrays.stream(data.split("")) |
| ) |
| .collect(Collectors.toList()); |
| System.out.println(JSON.toJSONString(transform)); |
| |
| |
| int[][] array = {{1, 2}, {3, 4}, {5, 6}}; |
| int[] flatArray = Arrays.stream(array) |
| .flatMapToInt(Arrays::stream) |
| .toArray(); |
| System.out.println(Arrays.toString(flatArray)); |
| |
| |
| class Person { |
| private String name; |
| private List<String> hobbies; |
| |
| |
| } |
| |
| List<Person> personList = Arrays.asList( |
| new Person("Alice", Arrays.asList("reading", "swimming")), |
| new Person("Bob", Arrays.asList("hiking", "cooking")) |
| ); |
| List<String> hobbyList = personList.stream() |
| .flatMap(person -> person.getHobbies().stream()) |
| .collect(Collectors.toList()); |
| System.out.println(hobbyList); |
| |
| |
| List<Person> people = Arrays.asList( |
| new Person("John", 30), |
| new Person("Jane", 25), |
| new Person("Bob", 40) |
| ); |
| List<Integer> ages = people.stream() |
| .filter(person -> person.getAge() > 30) |
| .map(Person::getAge) |
| .flatMap(age -> Stream.of(age)) |
| .collect(Collectors.toList()); |
| |
10.Java中FindFirst、findAny 查找使用.
- 介绍
- findAny查找前流中的任意元素
- findFirst查找第一个元素
- 实例
| |
| public class Menu { |
| |
| |
| |
| |
| private String name; |
| |
| |
| |
| private Double price; |
| |
| |
| |
| private Double kilo; |
| |
| |
| |
| private String type; |
| } |
| |
| Menu pork = new Menu("猪肉", 9.9, 10.0, "肉类"); |
| Menu beef = new Menu("牛肉", 38.8, 5.0, "肉类"); |
| Menu chicken = new Menu("鸡肉", 6.5, 30.0, "肉类"); |
| Menu tomato = new Menu("土豆", 3.5, 30.0, "蔬菜"); |
| Menu potato = new Menu("西红柿", 7.5, 20.0, "蔬菜"); |
| Menu apple = new Menu("苹果", 3.5, 20.0, "水果"); |
| Menu orange = new Menu("橙子", 4.0, 20.0, "水果"); |
| List<Menu> menuList = Arrays.asList(pork, beef, chicken, tomato, potato, apple, orange); |
| |
| |
| menuList.stream().filter(menu -> menu.getType().equals("水果")).findFirst().ifPresent(menu -> System.out.println(menu.getName())); |
| |
| |
| Optional<Menu> fruitMenu = menuList.stream().filter(menu -> menu.getType().equals("水果")).findAny(); |
| |
| |
| Optional<Menu> fruitMenu = menuList.stream().filter(menu -> menu.getType().equals("水果")).findFirst(); |
| if (fruitMenu != null && fruitMenu.isPresent() && fruitMenu.get().getName() != null) { |
| System.out.println(fruitMenu.get().getName() +"--"+fruitMenu.get().getPrice()); |
| } |
| |
| |
11.Java中Limit使用.
- 介绍
- limit 方法会限制输出值个数,入参是限制的个数大小
- 实例
| public void testLimit(){ |
| List<String> list = new ArrayList<String>() {{ |
| add("1"); |
| add("2"); |
| add("3"); |
| }}; |
| list.stream() |
| .map(s -> Integer.valueOf(s)) |
| .limit(2L) |
| .collect(Collectors.toList()); |
| } |
12.Java中Max,Min使用.
- 介绍
- 通过max、min方法,可以获取集合中最大、最小的对象
- 实例
| public void testMaxMin(){ |
| List<String> list = new ArrayList<String>() {{ |
| add("1"); |
| add("2"); |
| add("2"); |
| }}; |
| list.stream().max(Comparator.comparing(s -> Integer.valueOf(s))).get(); |
| list.stream().min(Comparator.comparing(s -> Integer.valueOf(s))).get(); |
| } |
13.Java中 匹配 anyMatch allMatch noneMatch使用.
-
介绍
-
示例
| |
| |
| boolean isVegetables = menuList.stream().anyMatch(menu -> menu.getType().equals("蔬菜")); |
| System.out.println(isVegetables); |
| |
| |
| |
| boolean isAllVegetables = menuList.stream().allMatch(menu -> menu.getType().equals("蔬菜")); |
| System.out.println(isAllVegetables); |
| |
| |
| |
| boolean isNoneDrink = menuList.stream().noneMatch(menu -> menu.getType().equals("酒水")); |
| System.out.println(isNoneAllVegetables); |
14.Java中归约 reduce使用.
- 介绍
- 示例
| |
| double totalPrice = menuList.stream().map(Menu::getPrice).reduce(0.0, (a, b) -> a + b); |
| System.out.println(totalPrice); |
| |
| |
| double totalPrice = menuList.stream().map(menu -> {return new BigDecimal(menu.getPrice());}).reduce(BigDecimal.ZERO, BigDecimal::add).doubleValue(); |
| System.out.println(totalPrice); |
| |
| |
| double maxPrice = menuList.stream().map(Menu::getPrice).reduce(Double::max).get(); |
| System.out.println(maxPrice); |
15.Java中 数值范围 range rangeClosed使用.
- 介绍
- 示例
| |
| IntStream is = IntStream.rangeClosed(1, 100).filter(i -> i % 2 == 0); |
| is.forEach(System.out::println); |
| |
| |
| |
| LongStream ls = LongStream.range(1, 100); |
| ls.forEach(System.out::println); |
| |
| |
16.Java中 值创建流使用.
- 介绍
- 示例
| Stream<String> ss = Stream.of("ilob", "beh", "jb"); |
| ss.map(String::toUpperCase).forEach(System.out::println); |
| |
17.Java中 数值流 mapToDouble、mapToLong、mapToInt使用.
- 介绍
- 示例
| |
| |
| double sum = menuList.stream().mapToDouble(Menu::getPrice).sum(); |
| System.out.println(sum); |
| |
| |
| |
| DecimalFormat df = new DecimalFormat(); |
| df.setRoundingMode(RoundingMode.HALF_UP); |
| |
| double sum = menuList.stream().mapToDouble(Menu::getPrice).sum(); |
| System.out.println(df.format(sum)); |
| |
| |
| |
| List<Long> longList = Arrays.asList(1L, 2L, 3L, 4L); |
| long longsum = longList.stream().mapToLong(Long::longValue).sum(); |
| System.out.println(longsum); |
| |
| |
| |
| List<String> list = Arrays.asList("apple", "banana", "orange", "kiwi"); |
| int sum = list.stream().mapToInt(str -> str.length()).sum(); |
| System.out.println("Sum of length: " + sum); |
18.Java中 收集器使用.
- 介绍
- 示例
| |
| |
| long count = menuList.stream().count(); |
| System.out.println(count); |
| System.out.println(menuList.stream().collect(Collectors.counting())); |
| |
| |
| |
| double max = menuList.stream().collect(Collectors.maxBy(Comparator.comparing(Menu::getPrice))).get().getPrice(); |
| System.out.println(max); |
| |
| |
| |
| double min = menuList.stream().collect(Collectors.minBy(Comparator.comparing(Menu::getPrice))).get().getPrice(); |
| System.out.println(min); |
| |
| |
| |
| double sum = menuList.stream().collect(Collectors.summingDouble(Menu::getKilo)); |
| System.out.println(sum); |
| |
| |
| |
| DecimalFormat df = new DecimalFormat("#.00"); |
| df.setRoundingMode(RoundingMode.HALF_UP); |
| double avg = menuList.stream().collect(Collectors.averagingDouble(Menu::getKilo)); |
| System.out.println(df.format(avg)); |
| |
| |
| |
| DoubleSummaryStatistics dss = menuList.stream().collect(Collectors.summarizingDouble(Menu::getPrice)); |
| System.out.println(dss); |
19.Java中Collectors.joining使用.
- 介绍
- 实例
请点击
非流操作
1.Java中groupingBy使用.
- 介绍
- groupingBy 是能够根据字段进行分组
- toMap 是把 List 的数据格式转化成 Map 的格式
- 实例
| |
| public void testGroupBy(){ |
| List<String> list = new ArrayList<String>() {{ |
| add("1"); |
| add("2"); |
| add("2"); |
| }}; |
| Map<String, List<String>> strList = list.stream().collect(Collectors.groupingBy(s -> { |
| if("2".equals(s)) { |
| return "2"; |
| }else { |
| return "1"; |
| } |
| })); |
| } |
| |
| |
| Map<String, List<Product>> prodMap= prodList.stream().collect(Collectors.groupingBy(Product::getCategory)); |
| |
| |
| prodList.stream() |
| .collect(Collectors.groupingBy(Product::getCategory, Collectors.counting())); |
| |
| |
| prodList.stream() |
| .collect(Collectors.groupingBy(Product::getCategory, Collectors.summingInt(Product::getNum))); |
2.Java中Collect使用.
- 介绍
- 实例
| |
| list.stream().map(s -> Integer.valueOf(s)).collect(Collectors.toList()); |
| |
| |
| |
| |
| .collect(Collectors.toMap(String::valueOf, Function.identity())); |
| .collect(Collectors.toMap(PersonDto::getId, o -> o)); |
| |
| |
| Map<Long, String> collect = objects.stream().collect(Collectors.toMap(PersonDto::getId, PersonDto::getUserName)); |
| |
| |
| Map<Long, String> collect = objects.stream().collect(Collectors.toMap(PersonDto::getId, PersonDto::getUserName, (o1, o2) -> o1)); |
| |
| Map<Long, String> collect2 = objects.stream().collect(Collectors.toMap(PersonDto::getId, PersonDto::getUserName, (o1, o2) -> o2)); |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2021-04-19 String类型转换BigDecimal类型