是否有一种算法可以删除某些与另一个元素相同的元素?

时间:2020-05-19 20:09:40

标签: java list algorithm

我要删除与其他值相同的一些输出! 由于Test1 = Test2 = Test5 = Test6,所以我希望它在控制台上仅显示Test1! Test3 = Test4 = Test7 = Test8,所以我希望它仅显示Test3! ........

以下代码是我所做的:

    boolean flg1 = true;
    List<List<String>> tmp1 = new ArrayList <>();
    List<List<String>> tmp2 = new ArrayList <>();
    System.out.println();
    System.out.println("Size of the subset: " + subset.size());
    for(int i=0; i< subset.size();i++){
        tmp1=subset.get(i);

        // System.out.println("TMP1:"+ tmp1);

        for(int j=0; j<subset.size();j++){
        tmp2=subset.get(j);

        // System.out.println("TMP2:"+ tmp2.get(1));

            if(i != j && !compareOuterlist(tmp1,tmp2)){
                flg1=true;
                continue;
            }
        }
        if(flg1){
            count++;
            System.out.println("TEST " + (i+1) + ":"+ tmp1);
        }
    }

    System.out.println();
    System.out.println("Total partition:"+ count);
}
public static boolean compareOuterlist(List<List<String>> p1, List<List<String>> p2){
    if(p1.size() != p2.size()){
        return false;
    }
    for(int i = 0;i < p1.size();i++){
        if(!(compareInnerlist1(p1.get(i),p2.get(i)))){
            return false;
        }
    }
    return true;
}

public static boolean compareInnerlist1(List<String> p1, List<String> p2){
    for(int i=0;i<p1.size();i++){
        if(!(p1.equals(p2))){
            return false;
        }
    }
    return true;
}

以下是我的输出:

TEST 1:[[P11, X11, X22], [P11, X11, X22]]
TEST 2:[[P11, X11, X22], [P11, X11, X22]]
TEST 3:[[X11, X22], [P11, X22], [P11, X11]]
TEST 4:[[X11, X22], [P11, X22], [P11, X11]]
TEST 5:[[P11, X11, X22], [P11, X11, X22]]
TEST 6:[[P11, X11, X22], [P11, X11, X22]]
TEST 7:[[X11, X22], [P11, X22], [P11, X11]]
TEST 8:[[X11, X22], [P11, X22], [P11, X11]]
TEST 9:[[P11, X22], [X11, X22], [P11, X11]]
TEST 10:[[P11, X22], [X11, X22], [P11, X11]]
TEST 11:[[P11, X22], [X11, X22], [P11, X11]]
TEST 12:[[P11, X22], [X11, X22], [P11, X11]]

2 个答案:

答案 0 :(得分:0)

使用Java 8流,您可以使用distinct()

List<List<List<String>>> result = subset.stream().distinct().collect(Collectors.toList());

如果要在打印时循环执行此操作,可以使用Set

Set<List<List<String>>> distinct = new HashSet<>();
for (int i = 0; i < subset.size(); i++) {
    List<List<String>> tmp1 = subset.get(i);
    if (distinct.add(tmp1))
        System.out.println("TEST " + (i+1) + ":"+ tmp1);
}
System.out.println();
System.out.println("Total partition: " + distinct.size());

输出

TEST 1:[[P11, X11, X22], [P11, X11, X22]]
TEST 3:[[X11, X22], [P11, X22], [P11, X11]]
TEST 9:[[P11, X22], [X11, X22], [P11, X11]]

Total partition: 3

答案 1 :(得分:0)

您可以创建一个String的ArrayList,只要您想打印测试,就将结果添加到该List中,但是在打印和增加计数之前,您必须确保要打印的内容不存在。列表:

if(flg1){
        if !(Your_List.conatains("TEST " + (i+1) + ":"+ tmp1)) {
             System.out.println("TEST " + (i+1) + ":"+ tmp1);
             count++;
        }
        Your_List.add("TEST " + (i+1) + ":"+ tmp1);
    }