简体   繁体   English

如何比较许多字符串数组?

[英]How do I compare many string arrays?

I have many arrays of strings such as: 我有许多字符串数组,例如:

private String[] ar1= {"Cheese", "Pepperoni", "Books"};
private String[] ar2= {"Books", "Pepperoni", "Greatness"};
private String[] ar3= {"Whatever", "Whenever", "Pepperoni"};

How do I compare all these three arrays and get the results that a word "Pepperoni" is common between ar1, ar2 and ar3 or for example "Books" is common between only ar2 and ar1? 我如何比较所有这三个数组,并得出结果说,“ pepperoni”一词在ar1,ar2和ar3之间是常见的,或者例如“书”在ar2和ar1之间是常见的? I am able to compare two string arrays using for loops but how do do this for many such arrays? 我可以使用for循环比较两个字符串数组,但是如何对许多这样的数组执行此操作?

I would use a set 我会用一套

Set<String> words = new HashSet<>(Arrays.asList(ar1));
words.retainAll(Arrays.asList(ar2));
words.retainAll(Arrays.asList(ar3));

This takes the intersection of each of the arrays. 这需要每个数组的交集。

A more advanced option is to look at words which appear a number of times in many arrays. 一个更高级的选项是查看在许多数组中出现多次的单词。

Map<String, Long> words = Stream.of(ar1, ar2, ar3, ar4, ar5)
                               .flatMap(Stream::of)
                               .collect(Collectors.groupingBy(w -> w,
                                                              Collectors.counting()));

This gives you a Map of each word and how many times it appears. 这为您提供了每个单词及其出现次数的映射。 You can add more arrays as required. 您可以根据需要添加更多阵列。

You could create a dictionary where the keys are the words. 您可以创建一个字典,其中的关键是单词。 Now, you iterate over all words and add to the dictionary: 现在,您遍历所有单词并添加到字典中:

if the word is not in dict: 如果该词不是字典:

  dict[word] = 1;

else: 其他:

  dict[word]++;

At the end you iterate over the dictionary and all the keys that have value of 3 are the common between the tree arrays, this idea you could use for k arrays. 最后,您遍历字典,所有值均为3的键在树数组之间是公用的,这个想法可用于k个数组。 Also remember that first you have to eliminate the common words in the same array. 还请记住,首先必须消除同一数组中的常用词。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM