首页 > 解决方案 > 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]

标签: javaandroidarraysarraylist

解决方案


拿着:

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]

推荐阅读