加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

hashMap分别获取所有key和value

发布时间:2020-12-14 06:39:00 所属栏目:Java 来源:网络整理
导读:一直记不住,这次必须得自己记录一下了,遇到就查,太浪费时间了....虽然真的很基础的问题.... 1、code实现: public class Main { public static void main(String[] args){ // Scanner scanner=new Scanner(System.in);//在线笔试 HashMapInteger,Integer

一直记不住,这次必须得自己记录一下了,遇到就查,太浪费时间了....虽然真的很基础的问题....

1、code实现:

public class Main {
public static void main(String[] args){
// Scanner scanner=new Scanner(System.in);//在线笔试
HashMap<Integer,Integer> map=new HashMap<Integer,Integer>();
map.put(1,2);
map.put(2,3);
map.put(3,4);
map.put(4,4);

    //获取所有key
    Set<Integer> keys=map.keySet();
    Iterator<Integer> iterator1=keys.iterator();
    while (iterator1.hasNext()){
        System.out.print(iterator1.next() +",");
    }
    System.out.println();
    System.out.println("------------------------");

    //获取所有value
    Collection<Integer> values=map.values();
    Iterator<Integer> iterator2=values.iterator();
    while (iterator2.hasNext()){
        System.out.print(iterator2.next()+",");
    }
    System.out.println();
    System.out.println("------------------------");

    //去除value中重复值,相同值仅仅保留一个
    Set<Integer> valuesSimple=new HashSet<Integer>();
    for(int i:values){
        valuesSimple.add(i);
    }
    Iterator<Integer> iterator3=valuesSimple.iterator();
    while (iterator3.hasNext()){
        System.out.print(iterator3.next()+",");
    }
}

}

2、输出结果:

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读