字符串连接器
Java8中的字符串连接收集器在JDK8中,可以采用函数式编程(使用 Collectors.joining 收集器)的方式对字符串进行更优雅的连接。
Collectors.joining 收集器 支持灵活的参数配置,可以指定字符串连接时的 分隔符,前缀 和 后缀 字符串。
代码参考如下:
// 定义人名数组final String[] names = {"Zebe", "Hebe", "Mary", "July", "David"};Stream<String> stream1 = Stream.of(names);Stream<String> stream2 = Stream.of(names);Stream<String> stream3 = Stream.of(names);// 拼接成 [x, y, z] 形式String result1 = stream1.collect(Collectors.joining(", ", "[", "]"));// 拼接成 x | y | z 形式String result2 = stream2.collect(Collectors.joining(" | ", "", ""));// 拼接成 x -> y -> z] 形式String result3 = stream3.collect(Collectors.joining(" -> ", "", ""));System.out.println(result1);System.out.println(result2);System.out.println(result3);
程序输出结果如下:
[Zebe, Hebe, Mary, July, David]Zebe | Hebe | Mary | July | DavidZebe -> Hebe -> Mary -> July -> David
一般的做法(不推荐)
在JAVA8出现之前,我们通常使用循环的方式来拼接字符串,这样做不仅代码冗长丑陋,而且需要仔细阅读代码才知道代码的功能,例如下面的代码:
final String[] names = {"Zebe", "Hebe", "Mary", "July", "David"};StringBuilder builder = new StringBuilder();for (int i = 0; i < names.length; i++) {if (builder.length() > 1) {builder.append(",");}builder.append(names[i]);}System.out.println(builder.toString());
惰性求值
什么是惰性求值(惰性计算)惰性求值也叫惰性计算、延迟求职,在函数式编程语言中随处可见。可以这样通俗地理解为:不对给出的表达式立即计算并返回值,而是在这个值需要被用到的时候才会计算。这个是个人理解,有关专业的术语定义请参考百度百科:https://baike.baidu.com/item/惰性计算
————————————————
什么是及早求值(热情求值)和惰性求值相反的是及早求值(热情求值),这是在大多数编程语言中随处可见的一种计算方式,例如:
int x = 1;String name = getUserName();
上面的表达式在绑定了变量后就立即求值,得到计算的结果.
Java中的惰性求值
以下Java代码就是惰性求值的范例。这段代码在定义 nameStream 这个流的时候,System.out.println 语句不会被立即执行。
package me.zebe.cat.java.lambda;import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;/*** Java8惰性求值例子** @author Zebe*/public class LazyEvaluationDemo {/*** 运行入口** @param args 运行参数*/public static void main(String[] args) {// 定义流Stream<String> nameStream = Stream.of("Zebe", "July", "Yaha").filter(name -> {if (!name.isEmpty()) {System.out.println("过滤流,当前名称:" + name);return true;}return false;});// 取出流的值,这时候才会调用计算List<String> names1 = nameStream.collect(Collectors.toList());// 流只能被使用一次,下面这行代码会报错,提示流已经被操作或者关闭了List<String> names2 = nameStream.collect(Collectors.toList());}}
基本数据类型在高阶函数中的运用
众所周知,在Java中使用基本数据类型的性能和产效率远高于包装类型。由于装箱类型是对象,因此在内存中存在额外开销。比如,整型在内存中占用4 字节,整型对象却要占用 16 字节。这一情况在数组上更加严重,整型数组中的每个元素只占用基本类型的内存,而整型对象数组中,每个元素都是内存中的一个指针,指向 Java堆中的某个对象。在最坏的情况下,同样大小的数组, Integer[] 要比 int[] 多占用 6 倍内存。
将基本类型转换为装箱类型,称为装箱,反之则称为拆箱,两者都需要额外的计算开销。对于需要大量数值运算的算法来说,装箱和拆箱的计算开销,以及装箱类型占用的额外内存,会明显减缓程序的运行速度。
为了减小这些性能开销, Stream 类的某些方法对基本类型和装箱类型做了区分。Stream中的高阶函数 mapToLong 和其他类似函数即为该方面的一个尝试。在 Java 8 中,仅对整型、长整型和双浮点型做了特殊处理,因为它们在数值计算中用得最多,特殊处理后的系统性能提升效果最明显。
计算最大值、最小值、平均值、求和、计数统计
使用 mapToInt、mapToLong、mapToDouble 等高阶函数后,得到一个基于基本数据类型的流。针对这样的流,Java提供了一个摘要统计的功能(对应的类有:IntSummaryStatistics、LongSummaryStatistics 和 DoubleSummaryStatistics),如下代码所示:
/*** 运行入口** @param args 运行参数*/public static void main(String[] args) {toInt();toLong();toDouble();}private static void toInt() {IntSummaryStatistics statistics = Stream.of(1L, 2L, 3L, 4L).mapToInt(Long::intValue).summaryStatistics();System.out.println("最大值:" + statistics.getMax());System.out.println("最小值:" + statistics.getMin());System.out.println("平均值:" + statistics.getAverage());System.out.println("求和:" + statistics.getSum());System.out.println("计数:" + statistics.getCount());}private static void toLong() {LongSummaryStatistics statistics = Stream.of(1L, 2L, 3L, 4000000000000000000L).mapToLong(Long::longValue).summaryStatistics();System.out.println("最大值:" + statistics.getMax());System.out.println("最小值:" + statistics.getMin());System.out.println("平均值:" + statistics.getAverage());System.out.println("求和:" + statistics.getSum());System.out.println("计数:" + statistics.getCount());}private static void toDouble() {DoubleSummaryStatistics statistics = Stream.of(1, 2, 3.0, 5.2).mapToDouble(Number::doubleValue).summaryStatistics();System.out.println("最大值:" + statistics.getMax());System.out.println("最小值:" + statistics.getMin());System.out.println("平均值:" + statistics.getAverage());System.out.println("求和:" + statistics.getSum());System.out.println("计数:" + statistics.getCount());}
ThreadLocal的Lambda构造方式
Java8中ThreadLocal对象提供了一个Lambda构造方式,实现了非常简洁的构造方法:withInitial。这个方法采用Lambda方式传入实现了 Supplier 函数接口的参数。写法如下:
/*** 当前余额*/private ThreadLocal<Integer> balance = ThreadLocal.withInitial(() -> 1000);
银行存款实例
附带一个银行存款的例子。
package me.zebe.cat.java.lambda;/*** ThreadLocal的Lambda构造方式:withInitial** @author Zebe*/public class ThreadLocalLambdaDemo {/*** 运行入口** @param args 运行参数*/public static void main(String[] args) {safeDeposit();//notSafeDeposit();}/*** 线程安全的存款*/private static void safeDeposit() {SafeBank bank = new SafeBank();Thread thread1 = new Thread(() -> bank.deposit(200), "张成瑶");Thread thread2 = new Thread(() -> bank.deposit(200), "马云");Thread thread3 = new Thread(() -> bank.deposit(500), "马化腾");thread1.start();thread2.start();thread3.start();}/*** 非线程安全的存款*/private static void notSafeDeposit() {NotSafeBank bank = new NotSafeBank();Thread thread1 = new Thread(() -> bank.deposit(200), "张成瑶");Thread thread2 = new Thread(() -> bank.deposit(200), "马云");Thread thread3 = new Thread(() -> bank.deposit(500), "马化腾");thread1.start();thread2.start();thread3.start();}}/*** 非线程安全的银行*/class NotSafeBank {/*** 当前余额*/private int balance = 1000;/*** 存款** @param money 存款金额*/public void deposit(int money) {String threadName = Thread.currentThread().getName();System.out.println(threadName + " -> 当前账户余额为:" + this.balance);this.balance += money;System.out.println(threadName + " -> 存入 " + money + " 后,当前账户余额为:" + this.balance);try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}/*** 线程安全的银行*/class SafeBank {/*** 当前余额*/private ThreadLocal<Integer> balance = ThreadLocal.withInitial(() -> 1000);/*** 存款** @param money 存款金额*/public void deposit(int money) {String threadName = Thread.currentThread().getName();System.out.println(threadName + " -> 当前账户余额为:" + this.balance.get());this.balance.set(this.balance.get() + money);System.out.println(threadName + " -> 存入 " + money + " 后,当前账户余额为:" + this.balance.get());try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}}}
定制归一化收集器(reducing)得到自定义结果集
reducing简介reducing 是一个收集器(操作),从字面意义上可以理解为“减少操作”:输入多个元素,在一定的操作后,元素减少。
reducing 有多个重载方法,其中一个方法如下:
public static <T> Collector<T,?,Optional<T>> reducing(BinaryOperator<T> op)
以上方法,JDK对其的描述是:
Returns a Collector which performs a reduction of its input elements under a specified BinaryOperator. The result is described as an Optional. (返回一个收集器,该收集器在指定的二进制操作符下执行其输入元素的减少。结果被描述为可选的
reducing的应用reducing 是一个非常有用的收集器,可以用在多层流、下游数据分组或分区等场合。
下面是一个例子:
给定一组 Person 对象,每个 Person 都有 city(所在城市)和 height(身高)属性,编写一个程序,统计出每个不同的城市最大、最小身高值。
import java.util.*;import java.util.function.BinaryOperator;import static java.util.stream.Collectors.groupingBy;import static java.util.stream.Collectors.reducing;/*** ReducingDemo** @author Zebe*/public class ReducingDemo {/*** 运行入口** @param args 运行参数*/public static void main(String[] args) {List<Person> personList = getPersonList(1000000);functionStyle(personList);normalStyle(personList);}/*** 函数式编程风格(3行处理代码)* @param personList Person 列表*/private static void functionStyle(List<Person> personList) {long start = System.currentTimeMillis();// 创建一个比较器,取名为 byHeight (通过高度来比较)Comparator<Person> byHeight = Comparator.comparingInt(Person::getHeight);// 创建一个归一收集器Map<City, Optional<Person>> tallestByCity = personList.stream().collect(groupingBy(Person::getCity, reducing(BinaryOperator.maxBy(byHeight))));long usedTime = System.currentTimeMillis() - start;printResult("函数式编程风格", personList.size(), usedTime, tallestByCity);}/*** 普通编程风格(20行处理代码)* @param personList Person 列表*/private static void normalStyle(List<Person> personList) {long start = System.currentTimeMillis();// 创建一个结果集Map<City, Optional<Person>> tallestByCity = new HashMap<>();// 第一步:找出所有的不同城市Set<City> cityList = new HashSet<>();for (Person person : personList) {if (!cityList.contains(person.getCity())) {cityList.add(person.getCity());}}// 第二部,遍历所有城市,遍历所有人找出每个城市的最大身高for (City city : cityList) {int maxHeight = 0;Person tempPerson = null;for (Person person : personList) {if (person.getCity().equals(city)) {if (person.getHeight() > maxHeight) {maxHeight = person.getHeight();tempPerson = person;}}}tallestByCity.put(city, Optional.ofNullable(tempPerson));}long usedTime = System.currentTimeMillis() - start;printResult("普通编程风格", personList.size(), usedTime, tallestByCity);}/*** 获取Person列表* @param numbers 要获取的数量* @return 返回指定数量的 Person 列表*/private static List<Person> getPersonList(int numbers) {// 创建城市final City cityChengDu = new City("成都");final City cityNewYork = new City("纽约");List<Person> people = new ArrayList<>();// 创建指定数量的Person,并指定不同的城市和相对固定的身高值for (int i = 0; i < numbers; i++) {if (i % 2 == 0) {// 成都最大身高185people.add(new Person(cityChengDu, 185));} else if (i % 3 == 0) {people.add(new Person(cityChengDu, 170));} else if (i % 5 == 0) {// 成都最小身高160people.add(new Person(cityChengDu, 160));} else if (i % 7 == 0) {// 纽约最大身高200people.add(new Person(cityNewYork, 200));} else if (i % 9 == 0) {people.add(new Person(cityNewYork, 185));} else if (i % 11 == 0) {// 纽约最小身高165people.add(new Person(cityNewYork, 165));} else {// 默认添加纽约最小身高165people.add(new Person(cityNewYork, 165));}}return people;}/*** 输出结果* @param styleName 风格名称* @param totalPerson 总人数* @param usedTime 计算耗时* @param tallestByCity 统计好最大身高的城市分组MAP*/private static void printResult(String styleName, long totalPerson, long usedTime, Map<City, Optional<Person>> tallestByCity) {System.out.println("\n" + styleName + ":计算 " + totalPerson + " 个人所在不同城市最大身高的结果如下:(耗时 " + usedTime + " ms)");tallestByCity.forEach((city, person) -> {person.ifPresent(p -> System.out.println(city.getName() + " -> " + p.getHeight()));});}}
Person类
/*** Person** @author Zebe*/public class Person {/*** 所在城市*/private City city;/*** 身高*/private int height;/*** 构造器* @param city 所在城市* @param height 身高*/public Person(City city, int height) {this.city = city;this.height = height;}public City getCity() {return city;}public void setCity(City city) {this.city = city;}public int getHeight() {return height;}public void setHeight(int height) {this.height = height;}}
City类
/*** City** @author Zebe*/public class City {/*** 城市名*/private String name;/*** 构造器* @param name 城市名*/public City(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}}
注:以上代码如果要计算最小值、平均值,将 maxBy 换成 minBy 就可以了。
输出结果程序输出结果如下:
函数式编程风格:计算 1000000 个人所在不同城市最大身高的结果如下:(耗时 149 ms)成都 -> 185纽约 -> 200普通编程风格:计算 1000000 个人所在不同城市最大身高的结果如下:(耗时 82 ms)成都 -> 185纽约 -> 200
可以看出,函数式编程的效率不一定会比普通编程效率更高,甚至相对要慢一点,但是,函数式编程的好处在于:
把参数作为一个函数,而不是值,实现了只有在需要的时候才计算(惰性求值)。使用 lambda 表达式能够简化程序表达的含义,使程序更简洁明了。
Map新增的方法:computeIfAbsent
这个方法是JDK8中Map类新增的一个方法,用来实现当一个KEY的值缺失的时候,使用给定的映射函数重新计算填充KEY的值并返回结果。computeIfAbsent 方法的JDK源码如下:
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) {Objects.requireNonNull(mappingFunction);V v;// 尝试获取KEY的值,如果获取不到KEYif ((v = get(key)) == null) {V newValue;// 利用传入的计算函数,得到新的值if ((newValue = mappingFunction.apply(key)) != null) {// 将KEY的值填充为函数计算的结果put(key, newValue);// 返回计算的结果return newValue;}}// 如果KEY的值存在,则直接返回return v;}
computeIfAbsent使用例子
Map<String, String> cache = new HashMap<>();// 如果键的值不存在,则调用函数计算并将计算结果作为该KEY的值final String key = "myKey";cache.computeIfAbsent(key, s -> {System.out.println("根据" + s + "计算新的值");return "myCacheValue";});// 第一次get,会调用映射函数System.out.println(cache.get(key));// 第二次get,不会调用映射函数System.out.println(cache.get(key));
程序输出结果如下:
根据myKey计算新的值myCacheValuemyCacheValue
partitioningBy收集器
在JDK8中,可以对流进行方便的自定义分块,通常是根据某种过滤条件将流一分为二
例如:有一组人名,包含中文和英文,在 JDK8 中可以通过 partitioningBy 收集器将其区分开来。
下面是代码例子:
// 创建一个包含人名称的流(英文名和中文名)Stream<String> stream = Stream.of("Alen", "Hebe", "Zebe", "张成瑶", "钟其林");// 通过判断人名称的首字母是否为英文字母,将其分为两个不同流final Map<Boolean, List<String>> map = stream.collect(Collectors.partitioningBy(s -> {// 如果是英文字母,则将其划分到英文人名,否则划分到中文人名int code = s.codePointAt(0);return (code >= 65 && code <= 90) || (code >= 97 && code <= 122);}));// 输出分组结果map.forEach((isEnglishName, names) -> {if (isEnglishName) {System.out.println("英文名称如下:");} else {System.out.println("中文名称如下:");}names.forEach(name -> System.out.println("\t" + name));});
程序输出结果如下:
中文名称如下:张成瑶钟其林英文名称如下:AlenHebeZebe
高阶函数
什么是高阶函数高阶函数是指接受另外一个函数作为参数,或返回一个函数的函数。什么样的参数是函数类型的参数?要看该参数是否是一个函数式接口,函数式接口只会有一个方法,会使用 @FunctionalInterface 这个注解来修饰。
高阶函数在 Java8 中很常见,如以下的例子:
Stream<Integer> numUp = Stream.of(1, 2, 5).map(num -> num += 1);Stream<Integer> numbers = Stream.of(1, 2, -1, -5).filter(n -> n > 0);
如何判断高阶函数
Stream 的 anyMatch 是高阶函数吗?是的。因为它的参数接收的是另外一个函数:Predicate。
boolean greaterThanZero = Stream.of(-1, -2, 0, -5).anyMatch(num -> num > 0);
Stream 的 limit 是高阶函数吗?是的。因为它的返回值是一个Stream。
Stream
原文链接:
