不能用Hashmap一定要用LinkedHashMap因为是有序的
import java.util.LinkedHashMap;
import java.util.Map;
public class TestGeneral {
public static void main(String[] args) {
//store orignal User and Country
Map hmOriginal = new LinkedHashMap();
hmOriginal.put("John", "Canada");
hmOriginal.put("Bob", "USA");
hmOriginal.put("Tom", "USA");
hmOriginal.put("Alice", "Canada");
hmOriginal.put("Alan", "Canada");
hmOriginal.put("Peter", "UK");
//store Updated data
Map hmUpdated = new LinkedHashMap();
for (Map.Entry entry : hmOriginal.entrySet())
{
String sName = entry.getKey();
String sCountry = entry.getValue();
if( !hmUpdated.containsValue(sCountry))
{
hmUpdated.put(sName, sCountry);
}
}
System.out.println("Original data is :"+hmOriginal );
System.out.println("Updated data is :"+hmUpdated );
}
}
HashMap vs. LinkedHashMap
使用 LinkedHashMap,输出是:(正确)
Original data is :{John=Canada, Bob=USA, Tom=USA, Alice=Canada, Alan=Canada, Peter=UK}
Updated data is :{John=Canada, Bob=USA, Peter=UK}
使用 HashMap,输出是:(错误)
Original data is :{Tom=USA, Bob=USA, Alice=Canada, Alan=Canada, John=Canada, Peter=UK}
Updated data is :{Tom=USA, Alice=Canada, Peter=UK}
HashMap vs. LinkedHashMap
使用 LinkedHashMap,输出是:(正确)
Original data is :{John=Canada, Bob=USA, Tom=USA, Alice=Canada, Alan=Canada, Peter=UK}
Updated data is :{John=Canada, Bob=USA, Peter=UK}
使用 HashMap,输出是:(错误)
Original data is :{Tom=USA, Bob=USA, Alice=Canada, Alan=Canada, John=Canada, Peter=UK}
Updated data is :{Tom=USA, Alice=Canada, Peter=UK}