來源:blog.csdn.net/weixin_39723544/article/details/91359302
一、介紹
Java8更新後,Map接口中提供了compute方法。下面我們先看看官方文檔的對它的使用說明.
如果看完上面的還是不太明白的話,看下面的這個示例。然後再來看這段說明,你就明白的它的意思了。
二、使用
假如我們現在有一需求,需要統計一個字符串中各個單詞出現的頻率,然後從中找出頻率最高的單詞。讓我們先來看看jdk8之前的寫法。
public static void main(String[] args) {
String str = "hello java, i am vary happy! nice to meet you";
// jdk1.8之前的寫法
HashMap
result1 =
new HashMap<>(
32);
for (
int i =
0; i < str.length(); i++) {
char curChar = str.charAt(i);
Integer curVal = result1.get(curChar);
if (curVal ==
null) {
curVal =
1;
}
else {
curVal +=
1;
}
result1.put(curChar, curVal);
}
}
但是jdk8後,map給我們提供了更爲便捷的接口方法,那就是本文要說的重點compute方法。
public static void main(String[] args) {
String str = "hello java, i am vary happy! nice to meet you";
// jdk1.8的寫法
HashMap
result2 =
new HashMap<>(
32);
for (
int i =
0; i < str.length(); i++) {
char curChar = str.charAt(i);
result2.compute(curChar, (k, v) -> {
if (v ==
null) {
v =
1;
}
else {
v +=
1;
}
return v;
});
}
}
運行以上兩段代碼,發現運行的結構都是一樣的。
{ =9, a=5, !=1, c=1, e=4, h=2, i=2, j=1, l=2, ,=1, m=2, n=1, o=3, p=2, r=1, t=2, u=1, v=2, y=3}
在這裏可能有些同學不理解第二參數的含義,在這裏簡單說一下。推薦:Java面試練題寶典
Function作爲一個函數式接口,主要方法apply接收一個參數,返回一個值。這個有點類似數學中一元函數。
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
}
而 BiFunction則是Function函數的升級版。聰明的同學可能會發現Function只能接受一個參數。假如我的函數體有兩個參數,咋辦呢。而BiFunction正是解決這一問題而出現的。
這兩者的都不難。看示例。
@FunctionalInterface
public interface BiFunction<T, U, R> {
/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);
}
簡單示例:
// 求一個數的平方
Function
fun1= arg -> arg * arg;
Integer apply = fun1.apply(
10);
// 100
System.out.println(apply);
// 求輸入兩個的和
BiFunction
fun2 = (arg1, arg2) -> arg1 + arg2;
Integer sum = fun2.apply(
10,
20);
// 30
System.out.println(sum);
三、其他
Map接口的compute方法的二元函數。如果key不存在或者key對應的value爲null的話,則其value都是null。否則就是key對應的value值。(這點可以在官方文檔中體現出來)
本文分享自微信公衆號 - 架構真經(gentoo666)。
如有侵權,請聯繫 [email protected] 刪除。
本文參與“OSC源創計劃”,歡迎正在閱讀的你也加入,一起分享。