首页 > 解决方案 > 将数组转换为列表,然后转换为映射

问题描述

我想如果有人可以查看这段代码,代码应该将数组转换为列表,然后转换为地图。键应具有列表元素的值,如果是偶数,则该值应为 True,如果为奇数,则该值应为 False。数组是“8, 6, 1, 5, 3, 9, 2”。我很确定这是正确的方法,但是在打印地图时,我得到了很多线条,这是我第一次使用地图,所以我不确定这是否应该是这样,或者我搞砸了。代码:

    static public void toMap(int x[]) {
    List<Integer> list = new ArrayList<>();
    Map<Integer, String> map = new HashMap<>();
    for (int t : x) { 
        list.add(t); 
    }
        
    for(int z : list) {
        String tf;
        if(z % 2 == 0)
            tf = "True";
        else 
            tf = "False";
        map.put(z,tf);
        
        for (Map.Entry<Integer, String> mp : map.entrySet()) {
            System.out.println(mp.getKey() + "/" + mp.getValue());
        }
    }
}

打印时得到这个:

在此处输入图像描述

任何帮助/提示将不胜感激,在此先感谢!

标签: java

解决方案


您正在 for 循环内打印,这导致了问题。您需要将其移到 for 循环之外。这是更新的代码 -

    static public void toMap(int[] x) {
        List<Integer> list = new ArrayList<>();
        for (int t : x) {
            list.add(t);
        }

        Map<Integer, String> map = new HashMap<>();
        for(int z : list) {
            String tf;
            if(z % 2 == 0)
                tf = "True";
            else
                tf = "False";
            map.put(z,tf);
        }

        for (Map.Entry<Integer, String> mp : map.entrySet()) {
            System.out.println(mp.getKey() + "/" + mp.getValue());
        }
    }

您也可以将其简化如下 -

    public static void main(String[] args) {
        Integer[] array = {8, 6, 1, 5, 3, 9, 2};
        toMap(array);
    }

    static public void toMap(Integer[] x) {
        List<Integer> list = Arrays.asList(x);
        Map<Integer, String> map = new HashMap<>();
        list.forEach(i -> {
            if (i % 2 == 0)
                map.put(i, "True");
            else
                map.put(i, "False");
        });
        System.out.println(map);
    }

推荐阅读