对多个map进行遍历并取值

如果你只想输出自己想要的值不把取出的值放在另一个List里面可以不用list.add(),可以直接输出打印自己想要的值.

例一(不同类型的map遍历取值):

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ceshi {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();

        Map<String, Integer> map1 = new HashMap<>();
        map1.put("this is 1", 1);


        Map<String, Character> map2 = new HashMap<>();
        map2.put("this is a", 'a');

        Set<Map.Entry<String, Integer>> entries = map1.entrySet();
        for (Map.Entry<String, Integer> entry:entries) {
            Set<Map.Entry<String, Character>> entries1 = map2.entrySet();
            for (Map.Entry<String, Character> entry1 :entries1){
                list.add(entry.getKey()+"|"+entry1.getKey());
                list.add(entry.getKey()+"|"+ entry1.getValue());
                list.add(entry.getValue()+"|"+entry1.getKey());
                list.add(entry.getValue()+"|"+entry1.getKey());//把取出的值放在一个集合里面,取的值可以根据自己的需要,要key取key,要value取value.
            }
        }
        String  a = "";
        for (String o : list){
            a = o;
            System.out.println(a);
        }
    }
}

例二(对相同类型的map遍历取值):

import java.util.*;

public class CeShi1 {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        HashMap<String, Integer> map = new HashMap<>();
        map.put("张三",20);
        map.put("李四",22);
        HashMap<String, Integer> map1 = new HashMap<>();
        map1.put("王五",21);
        map1.put("赵六",23);
        HashMap<String, HashMap<String, Integer>> mapmax = new HashMap<>();
        mapmax.put("基础班",map);
        mapmax.put("就业班",map1);
        Set<Map.Entry<String, HashMap<String, Integer>>> entries = mapmax.entrySet();
        for (Map.Entry<String, HashMap<String, Integer>> entry : entries) {
//            System.out.println(entry.getKey());
            Set<Map.Entry<String, Integer>> entries1 = entry.getValue().entrySet();
            for (Map.Entry<String, Integer> stringIntegerEntry : entries1) {
                list.add(entry.getKey()+"\t"+stringIntegerEntry.getKey()+"     "+stringIntegerEntry.getValue());
            }
        }
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);
            System.out.println(s);
        }
    }
}

posted @ 2022-01-20 10:39  freedomAndWind  阅读(464)  评论(0编辑  收藏  举报