慢吞云雾缓吐愁 发表于 2022-8-13 03:19:05

Java之Map集合

一、Map

Map是java中的接口,Map.Entry是Map的一个内部接口。
Map提供了一些常用方法,如keySet()、entrySet()等方法。
keySet()方法返回值是Map中key值的集合;entrySet()的返回值也是返回一个Set集合,此集合的类型为Map.Entry。
Map.Entry是Map声明的一个内部接口,此接口为泛型,定义为Entry。它表示Map中的一个实体(一个key-value对)。接口中有getKey(),getValue方法。
Map<String, String> map = new HashMap<String, String>();
map.put(“key1”, “value1”);
map.put(“key2”, “value2”);
map.put(“key3”, “value3”); 
二、遍历

//第一种:普遍使用,二次取值
System.out.println(“通过Map.keySet遍历key和value:”);
for (String key : map.keySet()) {
  System.out.println("key= "+ key + " and value= " + map.get(key));

//第二种
System.out.println(“通过Map.entrySet使用iterator遍历key和value:”);
Iterator<Map.Entry<String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
  Map.Entry<String, String> entry = it.next();
  System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());

//第三种:推荐,尤其是容量大时
System.out.println(“通过Map.entrySet遍历key和value”);
for (Map.Entry<String, String> entry : map.entrySet()) {
  System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());

//第四种
System.out.println(“通过Map.values()遍历所有的value,但不能遍历key”);
for (String v : map.values()) {
    System.out.println("value= " + v);

三、排序

1 import java.util.Collections;
2 import java.util.HashMap;
3 import java.util.LinkedHashMap;
4 import java.util.Map;
5
6 import static java.util.Map.Entry.comparingByValue;
7 import static java.util.stream.Collectors.toMap;
8
9 public class SortTest {
10
11   public static void main(String[] args) throws Exception {
12
13         // 创建一个字符串为Key,数字为值的map
14         Map<String, Integer> budget = new HashMap<>();
15         budget.put("clothes", 120);
16         budget.put("grocery", 150);
17         budget.put("transportation", 100);
18         budget.put("utility", 130);
19         budget.put("rent", 1150);
20         budget.put("miscellneous", 90);
21         System.out.println("排序前: " + budget);
22
23         // 按值排序 升序
24         Map<String, Integer> sorted = budget
25               .entrySet()
26               .stream()
27               .sorted(comparingByValue())
28               .collect(
29                         toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
30                                 LinkedHashMap::new));
31
32         System.out.println("升序按值排序后的map: " + sorted);
33
34         // 按值排序降序
35         sorted = budget
36               .entrySet()
37               .stream()
38               .sorted(Collections.reverseOrder(comparingByValue()))
39               .collect(
40                         toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
41                                 LinkedHashMap::new));
42
43         System.out.println("降序按值排序后的map: " + sorted);
44   }
45
46
47 } 
封装成工具类
1 /**
2* Map排序工具类
3*
4* 5*/
6 public class MapSortUtil {
7   
8   private static Comparator<Map.Entry> comparatorByKeyAsc = (Map.Entry o1, Map.Entry o2) -> {
9         if (o1.getKey() instanceof Comparable) {
10             return ((Comparable) o1.getKey()).compareTo(o2.getKey());
11         }
12         throw new UnsupportedOperationException("键的类型尚未实现Comparable接口");
13   };
14
15
16   private static Comparator<Map.Entry> comparatorByKeyDesc = (Map.Entry o1, Map.Entry o2) -> {
17         if (o1.getKey() instanceof Comparable) {
18             return ((Comparable) o2.getKey()).compareTo(o1.getKey());
19         }
20         throw new UnsupportedOperationException("键的类型尚未实现Comparable接口");
21   };
22
23
24   private static Comparator<Map.Entry> comparatorByValueAsc = (Map.Entry o1, Map.Entry o2) -> {
25         if (o1.getValue() instanceof Comparable) {
26             return ((Comparable) o1.getValue()).compareTo(o2.getValue());
27         }
28         throw new UnsupportedOperationException("值的类型尚未实现Comparable接口");
29   };
30
31
32   private static Comparator<Map.Entry> comparatorByValueDesc = (Map.Entry o1, Map.Entry o2) -> {
33         if (o1.getValue() instanceof Comparable) {
34             return ((Comparable) o2.getValue()).compareTo(o1.getValue());
35         }
36         throw new UnsupportedOperationException("值的类型尚未实现Comparable接口");
37   };
38
39   /**
40      * 按键升序排列
41      */
42   public static <K, V> Map<K, V> sortByKeyAsc(Map<K, V> originMap) {
43         if (originMap == null) {
44             return null;
45         }
46         return sort(originMap, comparatorByKeyAsc);
47   }
48
49   /**
50      * 按键降序排列
51      */
52   public static <K, V> Map<K, V> sortByKeyDesc(Map<K, V> originMap) {
53         if (originMap == null) {
54             return null;
55         }
56         return sort(originMap, comparatorByKeyDesc);
57   }
58
59
60   /**
61      * 按值升序排列
62      */
63   public static <K, V> Map<K, V> sortByValueAsc(Map<K, V> originMap) {
64         if (originMap == null) {
65             return null;
66         }
67         return sort(originMap, comparatorByValueAsc);
68   }
69
70   /**
71      * 按值降序排列
72      */
73   public static <K, V> Map<K, V> sortByValueDesc(Map<K, V> originMap) {
74         if (originMap == null) {
75             return null;
76         }
77         return sort(originMap, comparatorByValueDesc);
78   }
79
80   private static <K, V> Map<K, V> sort(Map<K, V> originMap, Comparator<Map.Entry> comparator) {
81         return originMap.entrySet()
82               .stream()
83               .sorted(comparator)
84               .collect(
85                         Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
86                                 LinkedHashMap::new));
87   }
88
89 } 1 package com.chujianyun.common.map;
2
3 import org.junit.jupiter.api.BeforeAll;
4 import org.junit.jupiter.api.Test;
5 import org.junit.jupiter.api.TestInstance;
6
7 import java.util.HashMap;
8 import java.util.Map;
9
10
11 /**
12* Map排序工具类
13*
14*/
15 @TestInstance(TestInstance.Lifecycle.PER_CLASS)
16 class MapSortUtilTest {
17   // 创建一个字符串为Key,数字为值的map
18   Map<String, Integer> budget = new HashMap<>();
19
20   @BeforeAll
21   public void init() {
22         budget.put("clothes", 120);
23         budget.put("grocery", 150);
24         budget.put("transportation", 100);
25         budget.put("utility", 130);
26         budget.put("rent", 1150);
27         budget.put("miscellneous", 90);
28         System.out.println("排序前: " + budget);
29   }
30
31   @Test
32   void sortByKeyAsc() {
33         System.out.println("按键升序" + MapSortUtil.sortByKeyAsc(budget));
34   }
35
36   @Test
37   void sortByKeyDesc() {
38         System.out.println("按键降序" + MapSortUtil.sortByKeyDesc(budget));
39   }
40
41   @Test
42   void sortByValueAsc() {
43         System.out.println("按值升序" + MapSortUtil.sortByValueAsc(budget));
44   }
45
46   @Test
47   void sortByValueDesc() {
48         System.out.println("按值降序" + MapSortUtil.sortByValueDesc(budget));
49   }
50 } 

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
页: [1]
查看完整版本: Java之Map集合