英文:
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<String> ListDiff(List<String> a, List<String> b) {
return a.stream()
.filter(s->!b.contains(s))
.collect(Collectors.toList());
}
But note that if you were using Set
s instead of List
s, 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 = ['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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论