java - 如何在列表中只保留唯一值?- 爪哇
问题描述
基本上,我有一个模型,它存储两个值int keyScore
和List<Integer> moves
. 在主类中,我有一个从计算方法生成的模型列表。
我想做的是:
List<Integer>
如果 keyScore 等于,则连接移动- 删除重复项
当我找到相等的 keyScore 时,我尝试HashSet
在List<Integer>
移动中使用,但我最终得到了我的模型的重复项。
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();
}
您正在尝试分层合并。首先,您需要 unique s,并且对于要合并keyResult
的每个 unique s 。这是2级合并。keyResult
moves
( HashMap
- keyResult
> HeuristicResult
) 只保留唯一的keyResult
s 并将它们映射到HeuristicResult
它在列表中看到的第一个。然后在迭代过程中,如果它keyResult
再次找到相同的,它从地图中拉出moves
和在迭代中找到的那个并合并它们。合并Set
的被放回列表中(首先清除它)。
推荐阅读
- c - What i should use: strcpy or pointers?
- scala - 如何在没有 foreach() 的情况下使用 string.split()?
- php - PHP联系表格未提交并显示白屏
- r - 在 R 中构建灵敏度热图
- python - 如何获取 Python 方法的描述?
- amazon-web-services - 跨 AWS 账户使用 c7n-org 和 Cloud Custodian
- gradle - maven 或 gradle:如何找到依赖项开发者/提供者
- php - “安装失败,正在将 ./composer.json 还原为原始内容”怎么办?尝试通过作曲家在 laravel 上安装 Ignition 时?
- c# - 如何使用 ConfigurePrimaryHttpMessageHandler 泛型
- spring - 404错误springboot restcontroller请求映射