gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 16:39:08 25 4
gpt4 key购买 nike

我想删除与另一个具有相同值的一些输出!由于 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]]

最佳答案

使用 Java 8 Streams,您可以使用 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

关于java - 是否有一种算法可以删除某些与另一个相同的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61899903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com