就是简单的HashMap然后loop一次,loop的时候把国家名字保存在一个临时的HashSet里面。
每到新一行数据都检查已经保存的HashSet里面有没有这个国家,有的话删除这个元素,没有的话加到HashSet里面。HashMap是有remove方法的,所以很容易实现,注意iterator不要乱就行了。
不能用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<String , String> hmOriginal = new LinkedHashMap<String , String>();
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<String , String> hmUpdated = new LinkedHashMap<String , String>();
for (Map.Entry<String, String> 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 );
}
}
import java.util.LinkedHashMap;
import java.util.Map;
public class TestGeneral {
public static void main(String[] args) {
//store orignal User and Country
Map<String , String> hmOriginal = new LinkedHashMap<String , String>();
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<String , String> hmUpdated = new LinkedHashMap<String , String>();
for (Map.Entry<String, String> 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 );
}
}