【发布时间】:2017-11-14 04:18:45
【问题描述】:
我有一个带有字符串键和 MyObject 值的 ArrayList 的 HashMap,现在我想创建一个包含所有重叠 MyObjects 的列表的新列表。
例如:如果 ArrayList1 包含 MyObjectA、MyObjectB、MyObjectC,而 ArrayList2 包含 MyObjectA、MyObjectD、MyObjectE,那么我想将 MyObjectA - E 添加到新列表中,并将所有这些列表放入主列表中。如果任何值重叠,我想基本上将所有每个 ArrayList 的值组合到一个新列表中。
到目前为止,我只是遍历地图,遍历每个列表,然后再次嵌套迭代,如果任何值匹配,则对嵌套中的两个 ArrayLists 进行另一次迭代以将它们添加到不同的列表中,但这导致新列表中出现重复。
抱歉,如果这不是很清楚。
有没有人有任何建议或者更好的方法来完成这个?
谢谢!
这是我的代码:
public class DetermineOverlaps {
HashMap<String, ArrayList<CustomObject>> pgsPerStMap;
HashSet<HashSet<String>> competingPgs;
public DetermineOverlaps (HashMap<String, ArrayList<CustomObject>> pgsPerStMap2){
pgsPerStMap = new HashMap<String, ArrayList<CustomObject>>(pgsPerStMap2);
competingPgs = calculateCompetingPgs();
}
public HashSet<HashSet<String>> calculateCompetingPgs (){
//This will be the hashset which gets returned from this method
HashSet<HashSet<String>> competingProdGros = new HashSet<HashSet<String>>();
//I will iterate over each term (key) within the pgsPerStMap map, which contains search terms | all customObject for that search term
for (String searchTerm : pgsPerStMap.keySet()){
//I will iterate over each customObject for the search term
ArrayList<CustomObject> searchTermsPgs = pgsPerStMap.get(searchTerm);
for (CustomObject curProdGroup : searchTermsPgs){
String curProdGroupName = curProdGroup.key;
//I will store all found matches in this hashset, which I will later put in the competingProdGros map
HashSet<String> tempPgSet = new HashSet<String>();
//Compare every other key/value combination of the map to every other key/value combination of the map
for (String searchTerm2ndLevel : pgsPerStMap.keySet()){
//Iterate over the customObject
ArrayList<CustomObject> searchTermsPgsLev2 = pgsPerStMap.get(searchTerm2ndLevel);
for (CustomObject curProdGroup2ndLevel : searchTermsPgsLev2){
String curProdGroupLevel2Name = curProdGroup2ndLevel.key;
//If these are different keys, but the same value, i.e. you've got a value which has multiple
//overlapping keys, and the temporary hashset doesn't contain the value already
//Then add all values from both arraylist<CustomObject> into the temporary hashset...
if (!searchTerm2ndLevel.equals(searchTerm) && curProdGroupLevel2Name.equals(curProdGroupName)
&& !tempPgSet.contains(curProdGroupLevel2Name)){
for (CustomObject levelOnePg : searchTermsPgs){
String levelOnePgKey = levelOnePg.key;
tempPgSet.add(levelOnePgKey);
}
for (CustomObject levelTwoPg : searchTermsPgsLev2){
String levelTwoPgKey = levelTwoPg.key;
tempPgSet.add(levelTwoPgKey);
}
}
}
}
//Add the temporary hashset into the competingProdGros hashset
if(!competingProdGros.contains(tempPgSet)){competingProdGros.add(tempPgSet);}
}
}
//return the competingprodgros hashset
return competingProdGros;
}
【问题讨论】:
-
我认为CODE REVIEW 会更适合这个问题。
-
我推荐了解
List接口的addAll(联合)和retainAll(交集)方法。
标签: java list arraylist hashmap hashset