In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article focuses on "how to use the Map interface in Java8". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to use the Map interface in Java8.
Let's make a requirement: give a List
To count all the locations where each element appears
For example, given list: ["a", "b", "b", "c", "d", "f", "f", "g"], you should return:
A: [0] b: [1, 2] c: [3, 4, 5] d: [6, 7, 8] f: [9, 10] g: [11]
Obviously, we are well suited to use Map to do this:
Public static Map getElementPositions (List list) {Map positionsMap = new HashMap (); for (int I = 0; I
< list.size(); i++) { String str = list.get(i); List positions = positionsMap.get(str); if (positions == null) { // 如果 positionsMap 还不存在 str 这个键及其对应的 List positions = new ArrayList(1); positionsMap.put(str, positions); // 将 str 及其对应的 positions 放入 positionsMap } positions.add(i); // 将索引加入 str 相关联的 List 中 } return positionsMap;}public static void main(String[] args) throws Exception { List list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g"); System.out.println("使用 Java8 之前的 API:"); Map elementPositions = getElementPositions(list); System.out.println(elementPositions);} Java8 时, Map 接口添加了一个新的方法, putIfAbsent(K key, V value) ,功能是: 如果当前 Map 不存在键 key 或者该 key 关联的值为 null ,那么就执行 put(key, value) ;否则,便不执行 put 操作。该方法等价于如下代码: (题外话: putIfAbsent 方法与 put 方法一样,返回的是方法调用之前与参数 key 相关联的 value ) 使用 putIfAbsent 修改 getElementPositions 方法: public static Map getElementPositions(List list) { Map positionsMap = new HashMap(); for (int i = 0; i < list.size(); i++) { String str = list.get(i); positionsMap.putIfAbsent(str, new ArrayList(1)); // 如果 positionsMap 不存在键 str 或者 str 关联的 List 为 null,那么就会进行 put;否则不执行 put positionsMap.get(str).add(i); } return positionsMap;}public static void main(String[] args) throws Exception { List list = Arrays.asList("a", "b", "b", "c", "c", "c", "d", "d", "d", "f", "f", "g"); System.out.println("使用 putIfAbsent:"); Map elementPositions = getElementPositions(list); System.out.println(elementPositions);} 可以看到使用 putIfAbsent 之后的 getElementPositions 简洁了一点,那还能更简洁吗? 查看 Map 接口的方法,可以发现在 JDK1.8 时,还添加了如下两个方法: 查看 compute 方法的 API 文档,可以发现 compute 方法与如下代码等价 V oldValue = map.get(key); V newValue = remappingFunction.apply(key, oldValue); if (oldValue != null ) { if (newValue != null) map.put(key, newValue); else map.remove(key); } else { // 即 原来的 key 不存在 Map 中或该 key 关联的 value 为 null if (newValue != null) map.put(key, newValue); else return null; } compute 方法和原来 put 方法的区别在于: put(K key, V value) 方法,如果 key 在 Map 中不存在,那么直接加入;如果已经存在,那么使用新的 value 替换旧的 value ; 而 compute(K key, BiFunction remappingFunction) 方法可以通过一个 BiFunction 来计算出新的 value , BiFunction 的参数为旧的 key 和 value ,返回计算出新的 value -- 与 put 方法不同, compute 方法返回的会是最新的与 key 相关联的 value ,而不是旧的 value 。 所以可以使用 compute 方法改写 getElementPositions 如下: public static Map getElementPositions(List list) { Map positionsMap = new HashMap(); for (int i = 0; i < list.size(); i++) { positionsMap.compute(list.get(i), (k, v) ->V = = null? New ArrayList (1): v) .add (I);} return positionsMap;} public static void main (String [] args) throws Exception {List list = Arrays.asList ("a", "b", "b", "c", "d", "f", "f", "g"); System.out.println ("use compute:"); Map elementPositions = getElementPositions (list); System.out.println (elementPositions) }
(K, v)-> v = = null? New ArrayList (1): v means that if the current value is null, the return value of the BiFunction is new ArrayList (1); if it is not null, the return value is itself. And because the compute method returns the new value-- this is the ArrayList associated with list.get (I) (key)-- we can call its add method directly.
It's great. Can it be more concise? Let's take a look at the computeIfAbsent method: the relationship between computeIfAbsent and compute is similar to that between putIfAbsent and put: computeIfAbsent does not perform the operation of calculating the new value through the function when the key is not in the Map or the value associated with the key is null, otherwise it is not executed; the return value of computeIfAbsent is also the latest value associated with key. The default implementation is as follows:
Unlike compute, the function operation that computeIfAbsent accepts is Function rather than BiFunction-- it's understandable that computeIfAbsent only performs function operations when key is not in Map or the value associated with key is null, so obviously the value associated with key is null, so computeIfAbsent only accepts Function as an argument-- the Function can use key as an argument to calculate a new value. Use computeIfAbsent to rewrite getElementPositions:
Public static Map getElementPositions (List list) {Map positionsMap = new HashMap (); for (int I = 0; I
< list.size(); i++) { positionsMap.computeIfAbsent(list.get(i), k ->New ArrayList (1). Add (I);} return positionsMap;} public static void main (String [] args) throws Exception {List list = Arrays.asList ("a", "b", "b", "c", "c", "d", "f", "f", "g"); System.out.println ("use computeIfAbsent:"); Map elementPositions = getElementPositions (list); System.out.println (elementPositions);}
In fact, there is a problem when using putIfAbsent in this article, positionsMap.putIfAbsent (str, new ArrayList (1)); this code produces a temporary ArrayList every time it is called-- which may have a negative impact when the traversal List is large; the advantage of compute and computeIfAbsent, by contrast, is that they take an argument to a function and use the function to calculate the new value only when necessary. In the case of similar requirements in this article, computeIfAbsent is superior to compute in terms of applicability and simplicity. In the API documentation of JDK1.8, it is also mentioned that computeIfAbsent is suitable for this situation when you need to generate a structure similar to Map:
So what does the compute method apply to? As you can see from the previous introduction, the compute method is more suitable for situations where the new value depends on the old value when updating the value associated with the key-- such as counting the number of occurrences of each element in a List:
Public static Map getElementCounts (List list) {Map countsMap = new HashMap (); list.forEach (str-> countsMap.compute (str, (k, v)-> v = = null? 1: v + 1)); / / now: new value = old value + 1 return countsMap } public static void main (String [] args) throws Exception {List list = Arrays.asList ("a", "b", "b", "c", "c", "d", "f", "f", "g"); System.out.println ("using compute to calculate the number of occurrences of elements:"); Map counts = getElementCounts (list); System.out.println (counts);}
At this point, I believe you have a deeper understanding of "how to use the Map interface in Java8". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.