基本上,我有一个存储两个值int keyScoreList<Integer> moves的模型。在主类中,我具有从计算方法生成的此模型的列表。

我正在尝试做的是:


如果keyScore等于,则串联List<Integer>移动
删除重复项


当我找到相等的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();
}


您正在尝试分层合并。首先,您需要唯一的keyResult,对于每个要合并的keyResult,每个moves。这是2个合并级别。

HashMapkeyResult-> HeuristicResult)仅保留唯一的keyResult,并将它们映射到列表中看到的第一个HeuristicResult。然后,如果在迭代过程中再次找到相同的keyResult,则会从映射中拔出moves和在迭代中找到的Set并将其合并。合并的将放回到列表中(首先清除它)。

10-08 15:17