Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count distinct Strings in ArrayList without using Set?

Tags:

java

arraylist

How do you count the number of distinct Strings in an ArrayList without using the Set data structure in the Java libraries?

I made two ArrayLists, one stored and one empty and want to store the empty one with distinct Strings. What am I doing wrongly?

public void distinctCount (WordStream words) {
ArrayList<String> loaded = new ArrayList<String>();
  ArrayList<String> empty = new ArrayList<String>();
  int count = 0;

  // Fill loaded with word stream
  for(String i : words) {
    loaded.add(i);
  }

  // Fill empty with loaded
  // Catch collisions
  for(int i = 0; i < loaded.size(); i++) {
    if(loaded.get(i) != empty.get(i)) {
      empty.add(loaded.get(i));
    }
  }
  return empty.size();
}
like image 426
Naomi Avatar asked May 31 '26 06:05

Naomi


2 Answers

Here is a very bad / slow option you have:

for(String s: loaded){
    if(!empty.contains(s)){
        empty.add(s);
    }
}

or if you are Java 8 fan:

empty = loaded.stream().distinct().collect(Collectors.toList())
like image 194
dieter Avatar answered Jun 01 '26 21:06

dieter


The problem is that you're comparing only corresponding elements. Meaning that you compare the nth element with the nth element in the second arraylist.

The straightforward solution would be having nested loops: for each element in the first arraylist, loop over all elements in the second array list, if no match found - you know it's distinct. This solution's complexity is O(n2).

Of course there are many helpful methods in the ArrayList API that can make your life much easier. If there's no restriction on other data structures, you can consider using Map as well.

like image 32
Maroun Avatar answered Jun 01 '26 21:06

Maroun