Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

196
Views
Can I use HashMap of characters in place of String?

I want to have a function to build a String from inputted characters and stop building if it gets an input character that it contains.

I know I can use String.contains() for this but I am learning about HashMaps and am wondering if a faster way to do this could be storing the inputted characters in a HashMap and using the HashMap.contains() method.

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

HashMap::containsKey is O(1), String::contains is not. The implementation may change dependending of the JVM version but it's more something like O(n).

So yes, using an HashMap to look for a value should be faster (on small data you'll probably don't notice a difference) than calling String::contains. But a Map stores a key and a value, if you don't care about the value, you can use a Set (be careful, all the values are unique in this type of collection) because Set::contains is O(1).


As @n247s mentionned in the comment. Except if you really have a performance issue, String::contains should works fine and make the code simpler to read.

over 4 years ago · Santiago Trujillo Report

0

A Set would be a good data structure to use here.

Just take note of 1 thing though,

If you need case-sensitive search then you can use a HashSet. Example

Set<String> set = new HashSet<>();

Else, if you need case-insensitive search then a TreeSet. Example

Set<String> set = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
over 4 years ago · Santiago Trujillo Report

0

HashMap<> is just a class that extends the Map<> interface, you can use containsKey() or containsValue(). If you want to loop through the values in the HashMap, you can use the HashMaps.values() method and concat/add the value to the String.

UNTESTED:

int count = -1;
String new = "";
for (char c : map.values()) {
    count++;
    if (string.charAt(count).equals(c))
      break;
    new.concat(c);
}
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!