【发布时间】:2016-05-21 15:58:06
【问题描述】:
我这样拥有List<Map<String, String>> testList =new ArrayList<Map<String, String>>();。
我想根据前 5 个键从列表中删除重复的地图,最后 2 个键是可选的。
我尝试使用linkedhashset,它工作得很好,但是这段代码是遗留代码,它使用了很多比较器,我无法更改它并使用set。
Set<Map<String, String>> testList = new LinkedHashSet<Map<String, String>>();
ListOfMaps.java
public class ListOfMaps {
Map<String,String> map = new HashMap<String,String>();
List<Map<String, String>> testList =new ArrayList<Map<String, String>>();
public static void main(String[] args) {
ListOfMaps ll = new ListOfMaps();
ll.test();
}
public void test()
{
map = new HashMap<String,String>();
map.put("year", "2015");
map.put("standrad", "second");
map.put("age", "30");
map.put("gender", "M");
map.put("class", "first");
map.put("marks", "100");
map.put("score", "200");
testList.add(map);
map = new HashMap<String,String>();
map.put("year", "2015");
map.put("standrad", "second");
map.put("age", "31");
map.put("gender", "F");
map.put("class", "first");
map.put("marks", "100");
map.put("score", "200");
testList.add(map);
//This map object has duplicate keys year,standrad,age,gender,class same as like first map object .
//so this object should be ignore while adding into list.
//marks and score score keys are optional and need not to be verified.
map = new HashMap<String,String>();
map.put("year", "2015");
map.put("standrad", "second");
map.put("age", "30");
map.put("gender", "M");
map.put("class", "first");
map.put("marks", "100");
map.put("score", "200");
testList.add(map);
System.out.println(testList.toString());
}
}
谁能帮我解决这个问题?
谢谢
【问题讨论】:
-
当你真的应该拥有一个对象时,你正在使用数据结构。这是一个糟糕的设计。
-
我同意@duffymo,我会考虑创建一个“Person”类。
-
任何标准的 Java 集都只是简单地调用
hashcode()和equals()对放入其中的对象来确定唯一性。我不明白为什么 LinkedHashSet 不适合你。 -
@duffymo 这是退出,我们不能对遗留代码做任何事情。我们可以在这里做点什么吗?
-
对不起,如果它是遗留的,那么您将无能为力。你真的在问“我应该因为不想做正确的事而做一些愚蠢的事情吗?”我不支持。投票结束。