java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java Map常用方法

java中Map集合的常用方法总结大全

作者:sugarJava

开发中最常用的就是List集合和Map集合,Map集合是基于java核心类java.util中的,下面这篇文章主要给大家总结介绍了关于java中Map集合的一些常用方法,文中通过代码介绍的非常详细,需要的朋友可以参考下

1、如何把一个Map转化为List

日常开发中,我们经常遇到这种场景,把一个Map转化为List。map转List有以下三种转化方式:

示例代码:

//语法
/**
key 转list
List keyList = new ArrayList(map.keySet());

value转list
List valueList = new ArrayList(map.values());

//map转list
List entryList = new ArrayList(map.entrySet());
*/

public class Test {
    public static void main(String[] args) {
        Map<Integer,String> userMap=new HashMap<>();
        userMap.put(1, "刘备");
        userMap.put(2, "诸葛亮");
        userMap.put(3, "关羽");
        userMap.put(4, "张飞");
        userMap.put(5, "赵云");
        userMap.put(6, "黄忠");
        userMap.put(7, "马超");
        //把一个map的键转化成list
        List<Integer>keyList=new ArrayList<>(userMap.keySet());
        System.out.println(keyList);
        //把一个map的值转化成list
        List<String> valueList = new ArrayList<>(userMap.values());
        System.out.println(valueList);
        //把map的键值转化成list
        List entryList=new ArrayList(userMap.entrySet());
        System.out.println(entryList);
    }
}
------------------------------------------------------------------------
// 结果:
[1, 2, 3, 4, 5, 6, 7]
[刘备, 诸葛亮, 关羽, 张飞, 赵云, 黄忠, 马超]
[1=刘备, 2=诸葛亮, 3=关羽, 4=张飞, 5=赵云, 6=黄忠, 7=马超]  

2、如何遍历一个Map

我们经常需要遍历一个map,可以有以下两种方式实现:

通过entrySet+for实现遍历

public class Test {
    public static void main(String[] args) {
        Map<Integer,String> userMap=new HashMap<>();
        userMap.put(1, "刘备");
        userMap.put(2, "诸葛亮");
        userMap.put(3, "关羽");
        userMap.put(4, "张飞");
        userMap.put(5, "赵云");
        userMap.put(6, "黄忠");
        userMap.put(7, "马超");
        //把一个map的键转化成list
        List<Integer>keyList=new ArrayList<>(userMap.keySet());
     //   System.out.println(keyList);
        //把一个map的值转化成list
        List<String> valueList = new ArrayList<>(userMap.values());
       // System.out.println(valueList);
        //把map的键值转化成list
        List entryList=new ArrayList(userMap.entrySet());
      //  System.out.println(entryList);

//        for (Object o : entryList) {
//         String[] str=String.valueOf(o).split("=");
//            System.out.println(str[0]);
//            System.out.println(str[1]);
//        }

        for(Map.Entry entry:userMap.entrySet()){
            System.out.println(entry);
        }

    }
}
-----------------------------------------------
结果:
1=刘备
2=诸葛亮
3=关羽
4=张飞
5=赵云
6=黄忠
7=马超

通过Iterator+while实现遍历

public class Test {
    public static void main(String[] args) {
        Map<Integer,String> userMap=new HashMap<>();
        userMap.put(1, "刘备");
        userMap.put(2, "诸葛亮");
        userMap.put(3, "关羽");
        userMap.put(4, "张飞");
        userMap.put(5, "赵云");
        userMap.put(6, "黄忠");
        userMap.put(7, "马超");

        Iterator iterator=userMap.entrySet().iterator();

        while (iterator.hasNext()){
           Map.Entry entry=(Map.Entry)iterator.next();
           //get key
            Integer key=(Integer) entry.getKey();
            //get value
            String value=(String) entry.getValue();System.out.println("key:"+key+",value:"+value);

        }
        
    }
}
------------------------------------------------------------
    //结果:
key:1,value:刘备
key:2,value:诸葛亮
key:3,value:关羽
key:4,value:张飞
key:5,value:赵云
key:6,value:黄忠
key:7,value:马超  

3、如何根据Map的keys进行排序

对Map的keys进行排序,在日常开发很常见,主要有以下两种方式实现。

把Map.Entry放进list,再用Comparator对list进行排序

public class Test {
    public static void main(String[] args) {
        Map<String,String> userMap=new HashMap<>();
        userMap.put("104", "诸葛亮");
        userMap.put("106", "关羽");
        userMap.put("105", "张飞");
        userMap.put("107", "赵云");
        userMap.put("103", "黄忠");
        userMap.put("102", "马超");
        userMap.put("101", "刘备");

     List<Map.Entry<String,String>> list=new ArrayList<>(userMap.entrySet());
     Collections.sort(list, Comparator.comparing((Map.Entry e) -> e.getKey().toString()));

     for(Map.Entry entry:list){
         System.out.println("key:"+entry.getKey()+",value:"+entry.getValue());
     }

    }
}
------------------------------------------------
    //结果:
key:101,value:刘备
key:102,value:马超
key:103,value:黄忠
key:104,value:诸葛亮
key:105,value:张飞
key:106,value:关羽
key:107,value:赵云

使用SortedMap+TreeMap+Comparator实现

public class Test {
    public static void main(String[] args) {
        Map<String,String> userMap=new HashMap<>();
        userMap.put("104", "诸葛亮");
        userMap.put("106", "关羽");
        userMap.put("105", "张飞");
        userMap.put("107", "赵云");
        userMap.put("103", "黄忠");
        userMap.put("102", "马超");
        userMap.put("101", "刘备");

     SortedMap sortedMap=new TreeMap(new Comparator<String>(){

         @Override
         public int compare(String k1, String k2) {
             return k1.compareTo(k2);
         }
     });
        sortedMap.putAll(userMap);

        Iterator  itr=sortedMap.entrySet().iterator();
        while (itr.hasNext()){
            Map.Entry entry=(Map.Entry) itr.next();
            //get key
            String key=(String) entry.getKey();
            //get value
            String value=(String) entry.getValue();
            System.out.println("key:"+key+",value:"+value);
        }
    }
}
----------------------------------------------
   //结果:
key:101,value:刘备
key:102,value:马超
key:103,value:黄忠
key:104,value:诸葛亮
key:105,value:张飞
key:106,value:关羽
key:107,value:赵云

4、如何使用Map中的value进行排序

public class SortValuesMapTest {
 public static void main(String[] args) {
 Map<String, String> map = new HashMap<>();
        map.put("2010", "jay");
        map.put("1999", "whx");
        map.put("3010", "huaxiao");
 List <Map.Entry<String,String>>list = new ArrayList<>(map.entrySet());
 Collections.sort(list, (Map.Entry e1, Map.Entry e2)-> {
 return e1.getValue().toString().compareTo(e2.getValue().toString());
 }
 );
 for (Map.Entry entry : list) {
 System.out.println("key:" + entry.getKey() + ",value:" + entry.getValue());
 }
 }
}
 

5、如何初始化一个静态/不可变的Map

//初始化一个静态不可变的map,单单static final+static代码块还是不行的,如下:
public class Test1 {
 private static final Map <Integer,String>map;
  static { 
        map = new HashMap<Integer, String>() 
        map.put(1, "one");
        map.put(2, "two");
 }
 
 public static void main(String[] args) {
 
        map.put(3, "three");
 
 Iterator itr = map.entrySet().iterator();
 
 while(itr.hasNext()) {
 Map.Entry entry = (Map.Entry) itr.next(); 
 // get key
 Integer key = (Integer) entry.getKey(); 
 // get value
 String value = (String) entry.getValue();
  
 System.out.println("key:"+key+",value:"+value);
 
 }
 }
}
---------------------------------------------
//这里面,map继续添加元素(3,"three"),发现是OK的,运行结果如下:
key:1,value:one
key:2,value:two
key:3,value:three


-----------------------------------------------------------------------
//真正实现一个静态不可变的map,需要Collections.unmodifiableMap,代码如下:
public class Test2 {
 
 private static final Map<Integer, String> map;
 
 static {
 
 Map<Integer,String> aMap = new HashMap<>();
 
        aMap.put(1, "one");
 
        aMap.put(2, "two");
 
        map = Collections.unmodifiableMap(aMap);
 
 }
  
 public static void main(String[] args) { 
        map.put(3, "3");
 
 Iterator itr = map.entrySet().iterator();
 
 while(itr.hasNext()) { 
 Map.Entry entry = (Map.Entry) itr.next();
 // get key 
 Integer key = (Integer) entry.getKey();
 
 // get value
 String value = (String) entry.getValue(); 
 System.out.println("key:"+key+",value:"+value);

 }
 }
}
 ----------------------------------------------------
//真正实现一个静态不可变的map,需要Collections.unmodifiableMap,代码如下:
public class Test {
    private  static final Map<Integer,String> map; //凡是静态变量都得初始化
    static {
        Map<Integer,String>aMap=new HashMap<>();
        aMap.put(1,"one");
        aMap.put(2,"two");
        aMap.put(3,"three");
        aMap.put(4,"four");
        map = Collections.unmodifiableMap(aMap);
    }
    public static void main(String[] args) {
           map.put(5,"five");
    }
    Iterator itr=map.entrySet().iterator();
    while(itr. hasNext()){
        Map.Entry entry = (Map.Entry) itr.next();
        // get key
        Integer key = (Integer) entry.getKey();
        // get value
        String value = (String) entry.getValue();
        System.out.println("key:"+key+",value:"+value);
    }
}
------------------------------------------------
//结果:
Erro报错

6、如何创建一个空map

如果map是不可变的,可以这样创建:

Map map=Collections.emptyMap();
or
Map<String,String> map=Collections.<String, String>emptyMap(); 
//map1.put("1", "1"); 运行出错
---------------------------------
//如果你希望你的空map可以添加元素的,可以这样创建
Map map = new HashMap();

7、有关于map的复制

有关于hashmap的复制,在日常开发中,使用也比较多。主要有 =,clone,putAll,但是他们都是浅复制,使用的时候注意啦,可以看一下以下例子:

例子一,使用=复制一个map:

public class CopyMapAssignTest { 
 public static void main(String[] args) { 
 Map<Integer, User> userMap = new HashMap<>();
        userMap.put(1, new User("jay", 26));
        userMap.put(2, new User("fany", 25));
 //Shallow clone
 Map<Integer, User> clonedMap = userMap;
 //Same as userMap 
 System.out.println(clonedMap);
 System.out.println("\nChanges reflect in both maps \n");
 //Change a value is clonedMap
        clonedMap.get(1).setName("test");
 //Verify content of both maps
 System.out.println(userMap);
 System.out.println(clonedMap);
 }
}
 

运行结果:

{1=User{name='jay', age=26}, 2=User{name='fany', age=25}}
Changes reflect in both maps
{1=User{name='test', age=26}, 2=User{name='fany', age=25}}
{1=User{name='test', age=26}, 2=User{name='fany', age=25}}

从运行结果看出,对cloneMap修改,两个map都改变了,所以=是浅复制。

例子二,使用hashmap的clone复制:

public class CopyCloneMapTest { 
 public static void main(String[] args) {
 HashMap<Integer, User> userMap = new HashMap<>();
        userMap.put(1, new User("jay", 26));
        userMap.put(2, new User("fany", 25));
 //Shallow clone
 HashMap<Integer, User> clonedMap = (HashMap<Integer, User>) userMap.clone();
 //Same as userMap 
 System.out.println(clonedMap); 
 System.out.println("\nChanges reflect in both maps \n");
 
 //Change a value is clonedMap
 
        clonedMap.get(1).setName("test");

 //Verify content of both maps
 
 System.out.println(userMap);
 
 System.out.println(clonedMap);
 
 }
} 

运行结果:

{1=User{name='jay', age=26}, 2=User{name='fany', age=25}}

Changes reflect in both maps

{1=User{name='test', age=26}, 2=User{name='fany', age=25}}
 
{1=User{name='test', age=26}, 2=User{name='fany', age=25}}

从运行结果看出,对cloneMap修改,两个map都改变了,所以hashmap的clone也是浅复制。

例子三,通过putAll操作

public class CopyPutAllMapTest {
 public static void main(String[] args) {
 HashMap<Integer, User> userMap = new HashMap<>();
        userMap.put(1, new User("jay", 26));
        userMap.put(2, new User("fany", 25));
 //Shallow clone
 HashMap<Integer, User> clonedMap = new HashMap<>();
        clonedMap.putAll(userMap);
 //Same as userMap
 System.out.println(clonedMap);
 System.out.println("\nChanges reflect in both maps \n");
 //Change a value is clonedMap
        clonedMap.get(1).setName("test");
 //Verify content of both maps
 System.out.println(userMap);
 System.out.println(clonedMap);
 }
}
 

运行结果:

{1=User{name='jay', age=26}, 2=User{name='fany', age=25}}
Changes reflect in both maps
{1=User{name='test', age=26}, 2=User{name='fany', age=25}}
 
{1=User{name='test', age=26}, 2=User{name='fany', age=25}}

从运行结果看出,对cloneMap修改,两个map都改变了,所以putAll还是浅复制。

那么,如何实现深度复制呢?

可以使用序列化实现,如下为谷歌Gson序列化HashMap,实现深度复制的例子:

public class CopyDeepMapTest {
 public static void main(String[] args) {
 HashMap<Integer, User> userMap = new HashMap<>();
        userMap.put(1, new User("jay", 26));
        userMap.put(2, new User("fany", 25));
 //Shallow clone
 Gson gson = new Gson();
 String jsonString = gson.toJson(userMap);
 Type type = new TypeToken<HashMap<Integer, User>>(){}.getType();
 HashMap<Integer, User> clonedMap = gson.fromJson(jsonString, type);
 //Same as userMap
 System.out.println(clonedMap);
 System.out.println("\nChanges reflect in only one map \n");
 //Change a value is clonedMap
        clonedMap.get(1).setName("test");
 //Verify content of both maps
 System.out.println(userMap);
 System.out.println(clonedMap);
 }
}
 

运行结果:

{1=User{name='jay', age=26}, 2=User{name='fany', age=25}}

Changes reflect in only one map
 
{1=User{name='jay', age=26}, 2=User{name='fany', age=25}}
 
{1=User{name='test', age=26}, 2=User{name='fany', age=25}}

从运行结果看出,对cloneMap修改,userMap没有被改变,所以是深度复制。

总结

到此这篇关于java中Map集合的常用方法总结的文章就介绍到这了,更多相关java Map常用方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文