ANDROID:删除重复字符串

我在完全删除重复字符串时遇到问题List<String>


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<String>(Arrays.asList(myno));


List<String> stringList1 = new ArrayList<String>(Arrays.asList(myno1));


stringList.addAll(stringList1);


Set<String> set = new HashSet<>(stringList);

stringList.clear();

stringList.addAll(set);


System.out.println("=== s:" +stringList);

但我得到了这个:


=== s:[15, 13, 14, 11, 12, 08, 09, 04, 05, 06, 24, 07, 01, 02, 03, 10]


我希望结果是这样的:


=== s:[13, 14, 11, 12, 08, 09, 04, 05, 06, 24, 07, 02, 10]


临摹微笑
浏览 174回答 3
3回答

倚天杖

拿去:String[] myno1 = new String[]{"01", "02", "03", "04", "05", "06", "07",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "08", "09", "10", "11", "12", "13", "14", "15"};String[] myno2 = new String[]{"01", "03", "15"};// use LinkedHashSet to preserve orderSet<String> set1 = new LinkedHashSet<>(Arrays.asList(myno1));Set<String> set2 = new LinkedHashSet<>(Arrays.asList(myno2));// find duplicatesSet<String> intersection = new LinkedHashSet<>();intersection.addAll(set1);intersection.retainAll(set2);// remove duplicates from both setsSet<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]

PIPIONE

因为您必须从另一个列表中删除项目。HashSet<>()用于从同一数组列表中删除重复项。例如,如果列表包含 15 个两次和 3 个两次,那么它将在列表中保留一次。这是代码foreach(String str : stringList){stringList1.remove(str);}

慕盖茨4494581

如果你使用 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()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(string -> Collections.frequency(stringList, string) == 1)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .collect(Collectors.toList());System.out.println("=== s:" + newList);不需要那么多地更改您的代码。创建了一个没有插入重复元素的新列表。输出是:=== s:[02, 04, 05, 06, 07, 08, 09, 10, 11, 12, 13, 14]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java