`

今天帮人解决的一个Map的问题,不过有得优化,暂时贴在这里先

    博客分类:
  • java
阅读更多
/*
 * 问题: 
 * HashMap<String, Integer> h = new HashMap<String, Integer>();
 * h.put("李",4000); 
 * h.put("张", 1000); 
 * h.put("尹", 1000); 
 * h.put("廖", 5000);
 * 
 * 用JAVA写一个算法,要求找出工资相等的人的名字?(不考虑重复)
 */

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class TestMap {

	public static void main(String[] args) {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		map.put("李", 4000);
		map.put("张", 1000);
		map.put("尹", 1000);
		map.put("廖", 5000);

		Set<String> keys = map.keySet();

		// 工资类型,用set是因为添加到一样的工资的话,它会覆盖掉以前的
		Set<String> salarys = new HashSet<String>();

		// listTemp存放String[]{姓名,工资}
		List<String[]> listTemp = new ArrayList<String[]>();
		String[] strTemp;// {姓名,工资}
		for (String key : keys) {
			strTemp = new String[2];
			strTemp[0] = key;
			strTemp[1] = map.get(key) + "";
			salarys.add(strTemp[1]);
			listTemp.add(strTemp);
		}
		//工资,姓名[]
		Map<String, List<String>> mapTemp = new HashMap<String, List<String>>();
		List<String> names=null;//存放工资相同的人的名字
	
		for (String salary:salarys ) {
			names=new ArrayList<String>();
			for (int i = 0; i < listTemp.size(); i++) {
				if(listTemp.get(i)[1].equals(salary)){
					names.add(listTemp.get(i)[0]);
				}
			}
			mapTemp.put(salary, names);
		}

		System.out.println("****下面是测试*****");
		Set<String> testMapTemp = mapTemp.keySet();
		for(String temp:testMapTemp){
			System.out.println("工资为 "+temp+" 有");
			for(String name:mapTemp.get(temp)){
				System.out.print(name+"    ");
			}
			System.out.println();
		}
	}

}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics