为了账号安全,请及时绑定邮箱和手机立即绑定

ANDROID:删除重复字符串

ANDROID:删除重复字符串

临摹微笑 2023-04-26 15:21:43
我在完全删除重复字符串时遇到问题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]
查看完整描述

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]


查看完整回答
反对 回复 2023-04-26
?
PIPIONE

TA贡献1829条经验 获得超9个赞

因为您必须从另一个列表中删除项目。HashSet<>()用于从同一数组列表中删除重复项。例如,如果列表包含 15 个两次和 3 个两次,那么它将在列表中保留一次。


这是代码


foreach(String str : stringList){


stringList1.remove(str);

}


查看完整回答
反对 回复 2023-04-26
?
慕盖茨4494581

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]


查看完整回答
反对 回复 2023-04-26
  • 3 回答
  • 0 关注
  • 173 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信