您可以使用以下代码来实现您的需求:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> list = Arrays.asList(1, 2, 3, 2, 1, 3, 4, 5, 4, 6);
        Map<Integer, Integer> map = new HashMap<>();

        for (int num : list) {
            if (map.containsKey(num)) {
                map.put(num, map.get(num) + 1);
            } else {
                map.put(num, 1);
            }
        }

        for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
            System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
        }
    }
}

这段代码首先创建了一个HashMap<Integer, Integer>对象map,然后使用一个List<Integer>对象list进行循环遍历。

在循环中,首先判断map中是否已经存在当前数字num作为键。如果存在,则将对应的值加1;如果不存在,则将当前数字num作为键,值设为1。

最后,通过map.entrySet()方法遍历map中的所有键值对,并打印出每个键值对的键和值。

运行以上代码,输出结果如下:

Key: 1, Value: 2
Key: 2, Value: 2
Key: 3, Value: 2
Key: 4, Value: 2
Key: 5, Value: 1
Key: 6, Value: 1
java中new 一个HashMapInteger Integer map用一个list集合循环遍历mapmap中没有该数值则设置该数值为keyvalue 为1若有则value +1

原文地址: https://www.cveoy.top/t/topic/h1xM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录