-1

What's the method to tell how many different words there are in the ArrayList?

For example:

public static ArrayList<String> myArray = new ArrayList<String>();
myArray.add("a");
myArray.add("b");
myArray.add("a");
myArray.add("c");

And the output will be

there is 3 different word in this array.
Candy
  • 13
  • 3

4 Answers4

2

you can create a Set<> Object from this since it only contains unique objects. So all the dublicates will be eliminated. And the size of the Set will be the number of different words.

Set can be creates like

Set<String> mySet = new HashSet<String>(myArray);
int differentWords = mySet.size(); 

Try doing this.

Parth Satra
  • 513
  • 2
  • 16
2

There are several ways to accomplish this. The simplest one is to do an exhaustive search:

  • For each position i in the list, take a word at position i
  • For each position j greater than i, compare words at position i and position j
  • If the two words are the same, blank out the word at position j
  • Once you are done with the outer loop, check how many non-null strings you have left. That's the number of unique words in there

A more advanced approach is to place all strings into a set of strings, and then take the count of set elements. This can be accomplished in a single line of code. Check the documentation for the information on HashSe<T>.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

You can also check for duplicates before adding new elements

if(!myArray.contains('a'))
       myArray.add('a');
caps lock
  • 511
  • 3
  • 7
  • 20
0

once go through this link. How to count the number of occurrences of an element in a List. It may be useful to you.

Community
  • 1
  • 1
Rekha S
  • 73
  • 1
  • 1
  • 11