Ravichandra
Ravichandra

Reputation: 25

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?

Upvotes: 2

Views: 88

Answers (2)

Rey Cruz
Rey Cruz

Reputation: 384

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.

Upvotes: 0

Peter Lawrey
Peter Lawrey

Reputation: 533530

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.

Upvotes: 6

Related Questions