在一个集合中找到一个缺失的元素。

huangapple go评论68阅读模式
英文:

Find a missing element in a collection

问题

有两个包含一些字符串元素的列表。这些列表可能相等,或者第二个列表中可能缺少一些元素。

任务是比较这两个列表,找到缺失的元素或第二个列表中缺少的元素,并将它们打印出来。

英文:

There are 2 lists containing some string elements. These lists may be equal or there may be some missing elements in second list.

The task is to compare these 2 lists and to find a missing emlenet or missing elements in second list and print them.

答案1

得分: 1

你可以尝试类似这样的代码:

public static List<String> ListDiff(List<String> a, List<String> b) {
    return a.stream()
            .filter(s -> !b.contains(s))
            .collect(Collectors.toList());
}

但请注意,如果你使用的是Set而不是List,可能会更快地使用removeAll

英文:

You could try something like that:

public static List&lt;String&gt; ListDiff(List&lt;String&gt; a, List&lt;String&gt; b) {
    return a.stream()
            .filter(s-&gt;!b.contains(s))
            .collect(Collectors.toList());
}

But note that if you were using Sets instead of Lists, you could use removeAll that would probably be much faster.

答案2

得分: -1

需要检查列表1中的每个元素是否在列表2中。如果存在,不执行任何操作。如果不存在,打印它。我会使用Python解决这个问题,因为这是我擅长的哈哈。

假设你的第一个列表是['A', 'B', 'C'],第二个列表是['A', 'B']。那么可以这样做:

list1 = ['A', 'B', 'C']
list2 = ['A', 'B', 'C']
if list1 == list2:
    print("Equal lists")
else:
    for i in list1:
        if i not in list2:
            print(i)
英文:

Basically, you need to check if each element of list 1 is in list 2 or not. It it's present, do nothing. If it's not, print it. I'm gonna solve this problem using python as that's what I'm good at haha.

Let us say your first list is ['A', 'B', 'C'] and the second list is ['A', 'B']. Then,

list1 = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]
list2 = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;]
if list1 == list2:
    print(&quot;Equal lists&quot;)
else:
    for i in list1:
        if i not in list2:
            print(i)

huangapple
  • 本文由 发表于 2023年2月27日 19:39:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579999.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定