Map集合保存值key倒序输出

//未获得Iterator对象用于迭代键

package test1;

import java.util.*;
//import java.util.Scanner;
//通过Map保存值并倒序打印

class Mycomparator implements Comparator{//自定义比较器比较
	public int compare(Object obj1,Object obj2) {
		String ele1=(String)obj1;
		String ele2=(String)obj2;
		return ele2.compareTo(ele1);//将 Number 对象与方法的参数进行比较。
	}
}
public class Main {
	public static void main(String[] args) {
	TreeMap map=new TreeMap(new Mycomparator());
	map.put("1","Lucy");
	map.put("4","Aimee");
	map.put("2","John");
	map.put("3","Smith");
	map.put("5","Amanda");
	for(Object key:map.keySet()) {//返回映射中所有 key 组成的 Set 视图。[5,4,3,2,1]
		System.out.println(key+":"+map.get(key));//get() 获取键对应的值
	}
 }		
}

结果

5:Amanda
4:Aimee
3:Smith
2:John
1:Lucy

//获得迭代键

package test1;

import java.util.*;
//import java.util.Scanner;
//通过Map保存值并倒序打印

class Mycomparator implements Comparator{//自定义比较器比较
	public int compare(Object obj1,Object obj2) {
		String ele1=(String)obj1;
		String ele2=(String)obj2;
		return ele2.compareTo(ele1);//将 Number 对象与方法的参数进行比较。
	}
}
public class Main {
	public static void main(String[] args) {
	TreeMap map=new TreeMap(new Mycomparator());
	map.put("1","Lucy");
	map.put("4","Aimee");
	map.put("2","John");
	map.put("3","Smith");
	map.put("5","Amanda");
	Set keySet=map.keySet();//获取键的集合
	Iterator it=keySet.iterator();//迭代键的集合
	//for(Object key:map.keySet()) {//返回映射中所有 key 组成的 Set 视图。[5,4,3,2,1]
	while(it.hasNext()) {
		Object key=it.next();
	System.out.println(key+":"+map.get(key));//get() 获取键对应的值
	}
 }	
}

结果

5:Amanda
4:Aimee
3:Smith
2:John
1:Lucy
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值