猿问

从Java中具有不同大小的2个数组列表中查找非相似元素

我有两个字符串类型的数组列表:


列出一个 -> [芒果、香蕉、苹果]


列表 b -> [Man, Apple]


我必须从两个列表中找出不相似的元素。


直到我实现了这个:


List d = new ArrayList(a);

toReturn.removeAll(b);

return d;

但是这段代码的问题是我不希望 Mango 作为列表 b 中的第一个元素包含“Man”字符串。我只想要返回“香蕉”。


红颜莎娜
浏览 199回答 2
2回答

aluckdog

您可以遍历一个列表并找到其中不是另一个列表的子字符串的项目,然后当然可以将参数颠倒过来:private static Stream<List> filterNonSimilar(List<String> a, List<String> b) {&nbsp; &nbsp; return a.stream()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(ai -> b.stream().noneMatch(bi -> ai.contains(bi) || bi.contains(ai));}public static List<String> nonSimilar(List<String> a, List<String> b) {&nbsp; &nbsp; return Stream.concat(filterNonSimilar(a, b), filterNonSimilar(b, a))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toList());}

胡说叔叔

您已经迭代了一个列表,然后必须在另一个列表中进行比较,如果第二个列表中存在该元素(反之亦然),则删除该元素,下面我将共享此方法的示例代码。public class Comp {public static void main(String... strings) {&nbsp; &nbsp; List<String> lis1 = new ArrayList<>();&nbsp; &nbsp; lis1.add("applefy");&nbsp; &nbsp; lis1.add("boy");&nbsp; &nbsp; lis1.add("carrr");&nbsp; &nbsp; List<String> lis2 = new ArrayList<>();&nbsp; &nbsp; lis2.add("apple");&nbsp; &nbsp; lis2.add("car");&nbsp; &nbsp; List<String> result = new ArrayList<>();&nbsp; &nbsp; for (String a : lis1) {&nbsp; &nbsp; &nbsp; &nbsp; for (String b : lis2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (a.contains(b)) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; result.add(a);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; lis1.removeAll(result);&nbsp; &nbsp; System.out.println(lis1);}} 输出:[男孩]希望这会有所帮助。
随时随地看视频慕课网APP

相关分类

Java
我要回答