0

I have Object Array named paragraph and a Hashmap Object named g_hMapValues. What I am doing in this code is iterating throughout the array paragraph and put it into the Text and Replacing the String (If it matched with the keys) corresponding to their hashmap values.

Note :- Please don't take care of class Text. it is working fine to me. What i need to do is optimize the logic (Nested Loop), because my paragraph may contains hundreds of thousands of records.

for(String keys : this.g_hMapValues.keySet()){ //hmapValues have some 20-30 key pair Values

        for (Object text : paragraph) { //paragraph may Contains 100000 of record.
            Text textElement = (Text) text;
            System.out.println(textElement.getValue());
            if (textElement.getValue().equalsIgnoreCase(keys)) {
                textElement.setValue(String.valueOf(this.g_hMapValues.get(keys)));
            }
        }
        }

I have a limited number of keys but it may exists in multiple paragraph and many times too. I didn't find any optimized logic to do that and it consumes so much time to respond to a REST Service.

I need to Optimize this iteration because during debugging i found that this iteration takes more time than usual.

James Z
  • 12,209
  • 10
  • 24
  • 44
Vikrant Kashyap
  • 6,398
  • 3
  • 32
  • 52

1 Answers1

1

You don't have to iterate through the hashmap's keySet. Iterate only through the paragraph array and check if the map contains current textElement. Example:

for (Object text : paragraph) { //paragraph may Contains 100000 of record.
    Text textElement = (Text) text;
    System.out.println(textElement.getValue());
    if (this.g_hMapValues.contains(textElement.getValue())) {
        textElement.setValue(String.valueOf(this.g_hMapValues.get(keys)));
    }
}

If case sensitivity is an issue, you can have a look at question Case insensitive string as HashMap key.

Community
  • 1
  • 1
radoh
  • 4,554
  • 5
  • 30
  • 45