3 回答
TA贡献1828条经验 获得超3个赞
拿去:
String[] myno1 = new String[]{"01", "02", "03", "04", "05", "06", "07",
"08", "09", "10", "11", "12", "13", "14", "15"};
String[] myno2 = new String[]{"01", "03", "15"};
// use LinkedHashSet to preserve order
Set<String> set1 = new LinkedHashSet<>(Arrays.asList(myno1));
Set<String> set2 = new LinkedHashSet<>(Arrays.asList(myno2));
// find duplicates
Set<String> intersection = new LinkedHashSet<>();
intersection.addAll(set1);
intersection.retainAll(set2);
// remove duplicates from both sets
Set<String> result = new LinkedHashSet<>();
result.addAll(set1);
result.addAll(set2);
result.removeAll(intersection);
System.out.println("Result: " + result);
Result: [02, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14]
TA贡献1829条经验 获得超9个赞
因为您必须从另一个列表中删除项目。HashSet<>()用于从同一数组列表中删除重复项。例如,如果列表包含 15 个两次和 3 个两次,那么它将在列表中保留一次。
这是代码
foreach(String str : stringList){
stringList1.remove(str);
}
TA贡献1850条经验 获得超11个赞
如果你使用 Java 8 或 +,你可以使用这个:
String[] myno1 = new String[] { "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15" };
String[] myno = new String[] { "01", "03", "15" };
List<String> stringList = new ArrayList<>(Arrays.asList(myno));
List<String> stringList1 = new ArrayList<>(Arrays.asList(myno1));
stringList.addAll(stringList1);
List<String> newList = stringList.stream()
.filter(string -> Collections.frequency(stringList, string) == 1)
.collect(Collectors.toList());
System.out.println("=== s:" + newList);
不需要那么多地更改您的代码。创建了一个没有插入重复元素的新列表。输出是:
=== s:[02, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14]
添加回答
举报