-1

There are various ways of doing the same thing however I'm looking for most efficient way here.

This is what I'm doing currently but there are going to be 5000+ entries that will all be added to girlNames. Not sure if its the right approach to do such thing and later compare it against given value.

Also appreciate if someone explain the logic behind why other method is better than this one.

Set<String> girlNames = new HashSet<String>();
girlNames.add("monica");
girlNames.add("ribeka");
girlNames.add("angelina");

String str = "angelina";
if (girlNames.contains(str.toLowerCase())) {
    System.out.println("found");
} else {
    System.out.println("not found");
}
Tom
  • 16,842
  • 17
  • 45
  • 54
linuxgenie
  • 77
  • 1
  • 8
  • 1
    Do you instead want to use a database? Please consider this, especially if many such comparisons will be done. – Hovercraft Full Of Eels Jun 19 '17 at 11:28
  • Do you want to store this information in DB later? Searching in DB will be faster – ByeBye Jun 19 '17 at 11:28
  • 7
    A `HashSet` is exactly the collection type that is appropriate for such a scenario: Adding and searching are operations with O(1) time complexity. – Seelenvirtuose Jun 19 '17 at 11:29
  • 1
    @Seelenvirtuose only if the objects stored overrides correctly `hashCode`. In case the OP use `String` it's already done but it's something to be aware of – Alberto S. Jun 19 '17 at 11:31
  • 2
    @Tom -- got it, thanks. – Hovercraft Full Of Eels Jun 19 '17 at 11:32
  • @Pelocho did i make any mistake in above code. how can i make sure it overrides correct hashCode. is there any study guide to refer for right coding practice with hashset . – linuxgenie Jun 19 '17 at 12:04
  • 1
    If you use `String` you're fine. But if using other objects and want to store them in any `Hash` structure you should override `hashCode()`. Check [this thread](https://stackoverflow.com/questions/3563847/what-is-the-use-of-hashcode-in-java) – Alberto S. Jun 19 '17 at 12:09

1 Answers1

2

Using a HashSet is completely fine for your purpose:

  • HashSets have look-up complexity of O(1) in the average case, meaning that the performance does not degrade for larger amounts of data.
  • 5000 Strings of that size can be easily kept memory. In a conservative estimate, each String object would require 1 KB of memory, totaling to 5 MB.
Sebastian Kruse
  • 318
  • 2
  • 7