java中List转Map以及map遍历的四种方式

原文地址:https://www.cnblogs.com/damoblog/p/9124937.html
方便自己查看,所以拷了一份到自己这边,方便查找

Java8List转map分组

Java8List转map分组 此处是根据名称作为key 分组

public Map<String, List<Student>> groupList(List<Student> students) {
    Map<String, List<Student>> map = students.stream().collect(Collectors.groupingBy(Student::getName));
    return map;
}

在java中所有的map都实现了Map接口,因此所有的Map(如HashMap, TreeMap, LinkedHashMap, Hashtable等)都可以用以下的方式去遍历。

方法一:在for循环中使用entries实现Map的遍历:

/**
* 最常见也是大多数情况下用的最多的,一般在键值对都需要使用
 */
Map <String,String>map = new HashMap<String,String>();
map.put("熊大", "棕色");
map.put("熊二", "黄色");
for(Map.Entry<String, String> entry : map.entrySet()){
    String mapKey = entry.getKey();
    String mapValue = entry.getValue();
    System.out.println(mapKey+":"+mapValue);
}

方法二:在for循环中遍历key或者values,一般适用于只需要map中的key或者value时使用,在性能上比使用entrySet较好;

Map <String,String>map = new HashMap<String,String>();
map.put("熊大", "棕色");
map.put("熊二", "黄色");
//key
for(String key : map.keySet()){
    System.out.println(key);
}
//value
for(String value : map.values()){
    System.out.println(value);
}

方法三:通过Iterator遍历:

Iterator<Entry<String, String>> entries = map.entrySet().iterator();
while(entries.hasNext()){
    Entry<String, String> entry = entries.next();
    String key = entry.getKey();
    String value = entry.getValue();
    System.out.println(key+":"+value);
}
方法四:通过键找值遍历,这种方式的效率比较低,因为本身从键取值是耗时的操作:
for(String key : map.keySet()){
    String value = map.get(key);
    System.out.println(key+":"+value);
}

list转map在Java8中stream的应用

  • 利用Collectors.toMap方法进行转换 <k,v>
public Map<Long, String> getIdNameMap(List<Account> accounts) {
    //key不会重复时候
    return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername));
    
    //key重复的时
    return accounts.stream().collect(Collectors.toMap(Account::getId, Account::getUsername, (key1, key2) -> key2));
   
}
  • 收集对象实体本身
  • 在开发过程中我们也需要有时候对自己的list中的实体按照其中的一个字段进行分组(比如 id ->List)这时候要设置map的value值是实体本身。
public Map<Long, Account> getIdAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getId, account -> account));
}

account -> account是一个返回本身的lambda表达式,其实还可以使用Function接口中的一个默认方法 Function.identity(),这个方法返回自身对象,更加简洁

重复key的情况。在list转为map时,作为key的值有可能重复,这时候流的处理会抛出个异常:Java.lang.IllegalStateException:Duplicate key。这时候就要在toMap方法中指定当key冲突时key的选择。(这里是选择第二个key覆盖第一个key)

public Map<String, Account> getNameAccountMap(List<Account> accounts) {
    return accounts.stream().collect(Collectors.toMap(Account::getUsername, Function.identity(), (key1, key2) -> key2));
}

用groupingBy 或者 partitioningBy进行分组 根据一个字段或者属性分组也可以直接用groupingBy方法,很方便

    Map<Integer, List<Person>> personGroups = Stream.generate(new PersonSupplier()).
     limit(100).
     collect(Collectors.groupingBy(Person::getAge));
    Iterator it = personGroups.entrySet().iterator();
    while (it.hasNext()) {
     Map.Entry<Integer, List<Person>> persons = (Map.Entry) it.next();
     System.out.println("Age " + persons.getKey() + " = " + persons.getValue().size());
    }

统计

Map<Stirng,Long>    overflowMap = ?     
if (CommonUtil.isNotEmpty(overflow.getList())){
            overflowMap =overflow.getList().stream().collect(Collectors.groupingBy(SmartDeviceDTO::getNzbm, Collectors.counting()));
        }

BigDdecimal 的求和

        BigDecimal result2 = userList.stream()
                // 将user对象的age取出来map为Bigdecimal
                .map(User::getAge)
                // 使用reduce()聚合函数,实现累加器
                .reduce(BigDecimal.ZERO,BigDecimal::add);

获取json中的key

    /**
     * 递归读取所有的key
     *
     * @param jsonObject
     */
    public static StringBuffer getAllKey(JSONObject jsonObject) {
        StringBuffer stringBuffer = new StringBuffer();
        Iterator<String> keys = jsonObject.keySet().iterator();// jsonObject.keys();
        while (keys.hasNext()) {
            String key = keys.next();
            stringBuffer.append(key.toString()).append("|");
            if (jsonObject.get(key) instanceof JSONObject) {
                JSONObject innerObject = (JSONObject) jsonObject.get(key);
                stringBuffer.append(getAllKey(innerObject));
            } else if (jsonObject.get(key) instanceof JSONArray) {
                JSONArray innerObject = (JSONArray) jsonObject.get(key);
                stringBuffer.append(getAllKey(innerObject));
            }
        }
        return stringBuffer;
    }

java 遍历Map及Map转化为二维数组的实例

 int a = 0, b = 0, c = 0;
    // 第一种:通过Map.keySet()遍历Map及将Map转化为二维数组
    Map<String, String> map1 = new HashMap<String, String>();
    map1.put("012013012013", "张三");
    map1.put("012013012014", "张四");
    String[][] group1 = new String[map1.size()][2];
    System.out.println("第一种:通过Map.keySet()遍历map1的key和value");
    for (String key : map1.keySet()) {
      System.out.println("key = " + key + " and value = " + map1.get(key));
      group1[a][0] = key;
      group1[a][1] = map1.get(key);
      a++;
    }
    System.out.println("map1.size()为:" + map1.size() + ",a为:" + a + ",group1数组的长度为:" + group1.length);
    System.out.println("----------------------------------------------------");
    for(int n = 0; n < group1.length; n++) {
      System.out.println("key = " + group1[n][0] + " and value = " + group1[n][1]);
    } 
 
    // 第二种:通过Map.entrySet()使用iterator()遍历Map及将Map转化为二维数组
    Map<String, String> map2 = new HashMap<String, String>();
    map2.put("112013012013", "李三");
    map2.put("112013012014", "李四");
    System.out.println("
" + "第二种:通过Map.entrySet()使用iterator()遍历map2的key和value");
    Iterator<Map.Entry<String, String>> iterator = map2.entrySet().iterator();
    String[][] group2 = new String[map2.size()][2];
    while (iterator.hasNext()) {
      Map.Entry<String, String> entry = iterator.next();
      System.out.println("key = " + entry.getKey() + " and value = " + entry.getValue());
      group2[b][0] = entry.getKey();
      group2[b][1] = entry.getValue();
      b++;
    }
    System.out.println("map2.size()为:" + map2.size() + ",b为:" + b + ",group2数组的长度为:" + group2.length);
    System.out.println("----------------------------------------------------");
    for(int n = 0; n < group2.length; n++) {
      System.out.println("key = " + group2[n][0] + " and value = " + group2[n][1]);
    } 
 
    // 第三种:通过Map.entrySet()遍历遍历Map及将Map转化为二维数组
    Map<String, String> map = new HashMap<String, String>();
    map.putAll(map1);
    map.putAll(map2);
    String[][] group3 = new String[map.size()][2];
    System.out.println("
" + "第三种:通过Map.entrySet()遍历map的key和value ");
    for (Map.Entry<String, String> entry : map.entrySet()) {
      System.out.println("key = " + entry.getKey() + " and value = " + entry.getValue());
      group3[c][0] = entry.getKey();
      group3[c][1] = entry.getValue();
      c++;
    }
    System.out.println("map.size()为:" + map.size() + ",c为:" + c + ",group3数组的长度为:" + group3.length);
    System.out.println("----------------------------------------------------");
    for(int n = 0; n < group3.length; n++) {
      System.out.println("key = " + group3[n][0] + " and value = " + group3[n][1]);
    } 
 
  }
}

多字段分组

public static void main(String[] args) {
    User user1 = new User("zhangsan", "beijing", 10);
    User user2 = new User("zhangsan", "beijing", 20);
    User user3 = new User("lisi", "shanghai", 30);
    List<User> list = new ArrayList<User>();
    list.add(user1);
    list.add(user2);
    list.add(user3);
    Map<String, List<User>> collect = list.stream().collect(Collectors.groupingBy(e -> fetchGroupKey(e)));
    //{zhangsan#beijing=[User{age=10, name='zhangsan', address='beijing'}, User{age=20, name='zhangsan', address='beijing'}], 
    // lisi#shanghai=[User{age=30, name='lisi', address='shanghai'}]}
    System.out.println(collect);
}
 
 
private static String fetchGroupKey(User user){
    return user.getName() +"#"+ user.getAddress();
}

JSONObject与对象互转

//Javabean对象转换成String类型的JSON字符串
JSONObject.toJSONString(Javabean对象)
 
//String类型的JSON字符串转换成Javabean对象
JSONObject.toJavaObject(JSON字符串,Javabean.class)
 
//Json字符串转换成JSONObject对象
JSONObject.parseObject(JSON字符串)
 
//JSON字符串转换成Javabean对象
JSONObject.parseObject(JSON字符串,Javabean.class)
 
例如
Refund r = new Refund();
String jsonStr = JSONObject.toJSONString(r);
 
 
String jsonStr = "{"msg":"ZhangSan"}";
Refund r = JSONObject.toJavaObject(jsonStr,Refund.class);
 
 
JSONObject jsonObject = JSONObject.parseObject(jsonStr);
 
 
Refund r = JSONObject.parseObject(jsonStr,Refund.class);