Posted in

Java 集合的函数式编程_AI阅读总结 — 包阅AI

包阅导读总结

1. 关键词:Java 集合、函数式编程、流操作、字符串处理、代码重用

2. 总结:这段文本主要介绍了使用 Java 集合进行函数式编程,对字符串进行排序、映射、过滤和规约等操作,并提及对规约操作的拓展思考,还强调了代码重用的重要性。

3. 主要内容:

– 对名字字符串进行一系列流操作

– 先按照姓氏倒序排序

– 提取每个名字的姓氏

– 过滤出长度大于等于 5 的姓氏

– 将姓氏用逗号连接成字符串

– 探讨了规约操作的拓展,如计算字符串字符数并返回整数

– 提到代码重用的重要性及在 Java 中创建函数式接口来共享操作的可能性

思维导图:

文章地址:https://www.infoworld.com/article/3481596/functional-programming-with-java-collections.html

文章来源:infoworld.com

作者:InfoWorld

发布时间:2024/8/14 9:00

语言:英文

总字数:1511字

预计阅读时间:7分钟

评分:82分

标签:函数式编程,Java 集合,流,Lambda,排序


以下为原文内容

本内容来源于用户推荐转载,旨在分享知识与观点,如有侵权请联系删除 联系邮箱 media@ilingban.com

String output = names.stream()      .sorted((name1, name2) -> {      String[] parts1 = name1.split(" ");      String lastName1 = parts1[parts1.length - 1];      String[] parts2 = name2.split(" ");      String lastName2 = parts2[parts2.length - 1];      return lastName2.compareTo(lastName1);    })    .map(name -> {      String[] parts = name.split(" ");      return parts[parts.length - 1];    })    .filter(lastName -> lastName.length() >= 5)    .reduce("", (accumulator, element) -> accumulator + element + ", ");    System.out.println("result: " + output);

This will concatenate all the strings together, joined by a comma. (We’ll have a trailing comma that we could drop off the end.)

reduce gives us an interesting look at a slightly more advanced area of streams. Consider if you wanted to count the string characters and return an integer value. How could you do that? The return value of reduce would want to be an integer, but the accumulator and element args are strings. I’ll leave that for an exercise, with this Stack Overflow question as one lead, and my introduction to Java stream gatherers as another.

Reusing operations

We’ve had a pretty good look at the way it feels to use and compose some of the most important Java functional operations. Another important facet is code reuse. Say you needed to use that fancy string sorter in several places. In Java, we could create a functional interface to share that operation: