简体   繁体   中英

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? I am able to compare two string arrays using for loops but how do do this for many such arrays?

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. Also remember that first you have to eliminate the common words in the same array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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