Java的map集合累计存入数据
其他问答
1
把遍历一个map集合中的值累计存入另一个map中,一个key对应多个值,不是只有一个…求大神指点。
-
package com.koolsee.xulonghui.test; import java.util.HashMap; import java.util.Map; public class Test { public static void main(String[] args) { Test t = new Test(); Map<Integer, User> map = new HashMap<Integer, User>(); map.put(1, t.new User(1, "zhansan", 1)); map.put(2, t.new User(2, "zhansan", 1)); map.put(3, t.new User(3, "lisi", 1)); map.put(4, t.new User(4, "lisi", 1)); map.put(5, t.new User(5, "wangwu", 1)); map.put(6, t.new User(6, "zhaoliu", 1)); System.out.println(getNameCount(map)); } private static Map<String, Integer> getNameCount(Map<Integer, User> map) { Map<String, Integer> resultMap = null; if ((map != null) && !map.isEmpty()) { resultMap = new HashMap<String, Integer>(); for (Integer key : map.keySet()) { User user = map.get(key); Integer count = resultMap.get(user.getName()); if (count != null) { resultMap.put(user.getName(), count + 1); } else { resultMap.put(user.getName(), 1); } } } return resultMap; } public class User { private Integer id; private String name; private Integer sex; public User(Integer id, String name, Integer sex) { super(); this.id = id; this.name = name; this.sex = sex; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Integer getSex() { return this.sex; } public void setSex(Integer sex) { this.sex = sex; } } }
-
package com.koolsee.xulonghui.test; import java.util.HashMap; import java.util.Map; public class Test { public static void main(String[] args) { Test t = new Test(); Map<Integer, User> map = new HashMap<Integer, User>(); map.put(1, t.new User(1, "zhansan", 1)); map.put(2, t.new User(2, "zhansan", 1)); map.put(3, t.new User(3, "lisi", 1)); map.put(4, t.new User(4, "lisi", 1)); map.put(5, t.new User(5, "wangwu", 1)); map.put(6, t.new User(6, "zhaoliu", 1)); System.out.println(getNameCount(map)); } private static Map<String, Integer> getNameCount(Map<Integer, User> map) { Map<String, Integer> resultMap = null; if ((map != null) && !map.isEmpty()) { resultMap = new HashMap<String, Integer>(); for (Integer key : map.keySet()) { User user = map.get(key); Integer count = resultMap.get(user.getName()); if (count != null) { resultMap.put(user.getName(), count + 1); } else { resultMap.put(user.getName(), 1); } } } return resultMap; } public class User { private Integer id; private String name; private Integer sex; public User(Integer id, String name, Integer sex) { super(); this.id = id; this.name = name; this.sex = sex; } public Integer getId() { return this.id; } public void setId(Integer id) { this.id = id; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Integer getSex() { return this.sex; } public void setSex(Integer sex) { this.sex = sex; } } }
发表回复