我是靠谱客的博主 贪玩绿草,这篇文章主要介绍Iterator迭代器遍历(List,Set,Map都通用),现在分享给大家,希望可以做个参考。

Iterator迭代器遍历(List,Set,Map都通用)

Iterator<Student> is=l.iterator();
  while(is.hasNext()){
  Student s=is.next();
   System.out.println(s.getName()+"t"+s.getAge());
  }

Map更常用的是通过Map.entrySet遍历key和value

public static void main(String[] args) {
        HashMap<Integer, String> hashmap = new HashMap<>();
        hashmap.put(1,"gogo");
        hashmap.put(2,"wade");
        hashmap.put(3,"james");
        hashmap.put(4,"curry");
 
        //3. 通过Map.entrySet遍历key和value
        for(Map.Entry<Integer, String> entry : hashmap.entrySet()){
            System.out.println("key: "+ entry.getKey() + "; value: " + entry.getValue());
        }

Java HashMap getOrDefault() 方法

getOrDefault() 方法获取指定 key 对应对 value,如果找不到 key ,则返回设置的默认值。

class Solution {
    public int majorityElement(int[] nums) {
        Map<Integer, Integer> counts = new HashMap<>();
        int length = nums.length;
        for (int i = 0; i < length; i++) {
            int count = counts.getOrDefault(nums[i], 0) + 1; //getOrDefault()返回的是nums[i]为key的value值
            if (count > length / 2)
                return nums[i];
            counts.put(nums[i], count);

        }
        return -1;

        第二种方法
        Arrays.sort(nums);
        return nums[nums.length / 2];
    }
}

最后

以上就是贪玩绿草最近收集整理的关于Iterator迭代器遍历(List,Set,Map都通用)的全部内容,更多相关Iterator迭代器遍历(List内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部