Map的computeIfAbsent使用場景和方法
1
2
3
|
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { ... } |
我們在復(fù)雜map操作(put操作)時候有的時候不知道此時當(dāng)前key對應(yīng)的value值是否存在,這里,我們?nèi)绻褂贸R?guī)的代碼編寫,代碼量比較大
例如我們定義一個場景:存在一個數(shù)組,我們需要將當(dāng)前數(shù)組中相同的數(shù)存儲到一個對應(yīng)List集合中
常規(guī)實現(xiàn)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
@Test public void test02() { //復(fù)雜map的使用場景:首先我們說復(fù)雜map,即map的value值為一個list集合或者是一個Set集合,對象或者是其他的集合 //給定一個場景:現(xiàn)在存在一個數(shù)組,我們需要將當(dāng)前數(shù)組中相同的數(shù)存儲到一個對應(yīng)List集合中 int [] nums = { 1 , 2 , 3 , 1 , 3 , 4 , 6 , 7 , 9 , 9 , 1 , 3 , 4 , 5 }; Map<Integer, List<Integer>> map = new HashMap<>(); //普通的寫法 for ( int i = 0 ; i < nums.length; i++) { if (!map.containsKey(nums[i])) { ArrayList<Integer> list = new ArrayList<>(); list.add(nums[i]); map.put(nums[i],list); } else { map.get(nums[i]).add(nums[i]); } } map.forEach((key,value) -> { System.out.print(key + ": " ); System.out.println(value); }); } |
使用computeIfAbsent方法實現(xiàn)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
@Test public void test03() { int [] nums = { 1 , 2 , 3 , 1 , 3 , 4 , 6 , 7 , 9 , 9 , 1 , 3 , 4 , 5 }; Map<Integer, List<Integer>> map = new HashMap<>(); //我們使用map的computeIfAbsent解決 for ( int i = 0 ; i < nums.length; i++) { //返回值是該key對應(yīng)的集合list map.computeIfAbsent(nums[i], key -> new ArrayList<Integer>()); map.get(nums[i]).add(nums[i]); } map.forEach((key,value) -> { System.out.print(key + ": " ); System.out.println(value); }); } |
輸出結(jié)果:
1: [1, 1, 1]
2: [2]
3: [3, 3, 3]
4: [4, 4]
5: [5]
6: [6]
7: [7]
9: [9, 9]
Map中computeIfAbsent() 的作用和底層實現(xiàn)
一、computeIfAbsent() 的作用
最近在開發(fā)中,發(fā)現(xiàn)同事經(jīng)常使用Map的computeIfAbsent()方法進行編程,于是對他的實現(xiàn)和作用產(chǎn)生了小興趣,下面用兩個demo案例來簡單介紹一下它的作用,然后再對底層實現(xiàn)進行進一步閱讀。
作用:判斷一個map中是否存在這個key,如果存在則處理value的數(shù)據(jù),如果不存在,則創(chuàng)建一個滿足value要求的數(shù)據(jù)結(jié)構(gòu)放到value中。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
public class TestComputeIfAbsent { static HashMap<String, Set<String>> hashMap = new HashMap<>(); public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add( "zhangSan" ); hashMap.put( "china" , set); // 判斷map中是否存在,如果存在則添加元素到set中,如果不存在則新建set添加到hashMap中 if (hashMap.containsKey( "china" )) { hashMap.get( "china" ).add( "liSi" ); } else { Set<String> setTmp = new HashSet<>(); setTmp.add( "liSi" ); hashMap.put( "china" , setTmp); } System.out.println(hashMap.toString()); } |
在使用了Map的computeIfAbsent() 方法后,使用后以上代碼變成了下面的形式(便捷、高效、代碼更加優(yōu)美,但可閱讀性降低):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public class TestComputeIfAbsent { static HashMap<String, Set<String>> hashMap = new HashMap<>(); public static void main(String[] args) { Set<String> set = new HashSet<>(); set.add( "zhangSan" ); hashMap.put( "china" , set); // after JDK1.8 hashMap.computeIfAbsent( "china" , key -> getValues(key)).add( "liSi" ); System.out.println(hashMap.toString()); } public static HashSet getValues(String key) { return new HashSet(); } } |
hashMap.computeIfAbsent(“china”, key -> getValues(key)).add(“liSi”);的意思表示key為“China”的建值對是否存在,返回的是value的值。
如果存在則獲取china的值,并操作值的set添加數(shù)據(jù)“lisi"。
如果不存在,則調(diào)用方法,新創(chuàng)建set結(jié)構(gòu),將"lisi"添加到set中,再存入到hashMap中。
二、computeIfAbsent() 的源碼實現(xiàn)
這個方法是JDK8中Map類新增的一個方法,用來實現(xiàn)當(dāng)一個KEY的值缺失的時候,使用給定的映射函數(shù)重新計算填充KEY的值并返回結(jié)果。computeIfAbsent 方法的JDK源碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
default V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { Objects.requireNonNull(mappingFunction); V v; // 嘗試獲取KEY的值,如果獲取不到KEY if ((v = get(key)) == null ) { V newValue; // 利用傳入的計算函數(shù),得到新的值 if ((newValue = mappingFunction.apply(key)) != null ) { // 將KEY的值填充為函數(shù)計算的結(jié)果 put(key, newValue); // 返回計算的結(jié)果 return newValue; } } // 如果KEY的值存在,則直接返回 return v; } |
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/SmallPig_Code/article/details/119647864