[英]How to leave only unique values in a List? - java
基本上,我有一個模型,該模型存儲兩個值: int keyScore
和List<Integer> moves
int keyScore
。 在主類中,我具有從計算方法生成的此模型的列表。
我正在嘗試做的是:
List<Integer>
移動 當我找到相等的keyScore時,我嘗試在List<Integer>
移動上使用HashSet
,但最終得到模型的重復項。
private class HeuristicResult {
private int keyResult;
private List<Integer> moves;
private HeuristicResult(int keyResult, List<Integer> moves) {
this.keyResult = keyResult;
this.moves = moves;
}
private int getKeyResult(){
return this.keyResult;
}
private List<Integer> getMoves(){
return this.moves;
}
private void setMoves(List<Integer> moves){
this.moves = moves;
}
@Override
public String toString() {
return String.format("%s : %s", this.keyResult, this.moves);
}
}
private List<HeuristicResult> concatHeuristicResults(List<HeuristicResult> heuristicResultsList){
List<HeuristicResult> heuristicResults = heuristicResultsList;
for(int i =0; i<heuristicResults.size()-2; i++){
int score = heuristicResults.get(i).getKeyResult();
for(int j = 0; j<heuristicResults.size()-1;j++){
if(score == heuristicResults.get(j).getKeyResult()){
heuristicResults.get(i).getMoves().addAll(heuristicResults.get(j).getMoves());
Set<Integer> temp = new HashSet<>(heuristicResults.get(i).getMoves());
heuristicResults.get(i).setMoves(new ArrayList<>(temp));
}
}
}
return heuristicResults;
}
這是我嘗試串聯時得到的輸出:
1 : [0, 1]
0 : [0, 1, 3, 6, 7, 8]
0 : [0, 1, 3, 6, 7, 8]
-10 : [3]
0 : [0, 1, 3, 6, 7, 8]
0 : [0, 1, 3, 6, 7, 8]
0 : [0, 1, 3, 6, 7, 8]
0 : [0, 1, 3, 6, 7, 8]
0 : [0, 1, 3, 6, 7, 8]
-1 : [0, 1, 7, 8]
0 : [0, 1, 3, 6, 7, 8]
0 : [0, 1, 3, 6, 7, 8]
0 : [0, 1, 3, 6, 7, 8]
-1 : [0, 1, 7, 8]
0 : [6]
0 : [6]
嘗試這個:
static Collection<HeuristicResult> concatenate(List<HeuristicResult> list) {
HashMap<Integer, HeuristicResult> keys = new HashMap<>();
for (HeuristicResult x: list) {
HeuristicResult hr = keys.get(x.keyResult);
if (hr != null) {
// Merge hr and x.
Set<Integer> moves = new HashSet<>();
moves.addAll(hr.getMoves());
moves.addAll(x.getMoves());
hr.moves.clear();
hr.moves.addAll(moves);
}
else {
// Create a new entry into our keys map if it doesn't exist.
keys.put(x.keyResult, x);
}
}
return keys.values();
}
您正在嘗試分層合並。 首先,你要獨特keyResult
S和每個這些獨特的keyResult
是你要合並moves
。 這是2個合並級別。
HashMap
( keyResult
> HeuristicResult
)僅保留唯一的keyResult
,並將它們映射到列表中看到的第一個HeuristicResult
。 然后,如果在迭代過程中再次找到相同的keyResult
,則會從地圖中提取moves
並在迭代中找到一個moves
並將其合並。 合並的Set
將放回到列表中(首先清除它)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.