-1

sorry if this is an stupid question or anything; but I'm having a problem looping through two different objects in java. one of them is a hashmap and the other one is an arraylist. the objects look something like this:

Map<String,Integer> myMap = new HashMap();
ArrayList<String> myArray = new ArrayList();

I need to loop through each item in "myArray" and check if the item exists in one of "myMap"'s keys. I actually know how to do that but the way I do it, contains a lot of unnecessary looping and I want to know if there is an faster way to do it or not. the way I do it:

Map<String,Integer> myMap = new HashMap();
ArrayList<String> myArray = new ArrayList();
        
        
for(String i:myArray) {
    for(String j:myMap.keySet()) {
        if(i == j) {
            myMap.put(j, myMap.get(j) + 1)
        }
    }
}
  • 2
    For starters, `Map` has a [`containsKey`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Map.html#containsKey(java.lang.Object)) method that could help you get rid of the inner loop. – Federico klez Culloca Aug 03 '21 at 08:37
  • Please use myMap.containsKey instead of 2nd for loop which will return true if the map contains specific key. – krishna Aug 03 '21 at 08:37
  • 3
    good to read: [How do I compare strings in Java?](https://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – jhamon Aug 03 '21 at 08:40
  • 1
    shouldn't `if(i == j)` actually be `if (i.equals(j))` instead? otherwise you're comparing references, not the content of the String. – Shark Aug 03 '21 at 09:07
  • yeah sorry, I'm used to python. java is new for me – alirezaba19 Aug 03 '21 at 10:41

3 Answers3

3

In Java 8 and later you can use a stream (I didn't see the increment, thx jhamon for the advice):

myArray.stream().filter(myMap::containsKey).forEach(
    item -> myMap.put(item, myMap.get(item) + 1)
  );
Reporter
  • 3,897
  • 5
  • 33
  • 47
3

You can alternativley use Map#computeIfPresent to get a one-liner like:

myArray.forEach(str -> myMap.computeIfPresent(str, (k,v) -> v+1) );
Eritrean
  • 15,851
  • 3
  • 22
  • 28
0

Following is the simple working example.

public class TestSample {

    public static void main(String[] args) {
        Map<String,Integer> myMap = new HashMap();
        myMap.put("some", 0);
        myMap.put("string", 0);
        
        ArrayList<String> myArray = new ArrayList<String>(Arrays.asList("some", "some", "string", "to", "check"));
        
        for(String i:myArray) {
            int val = myMap.getOrDefault(i, -1);
            if (val != -1)
                myMap.put(i, val+1);
        }
        System.out.println(myMap);      
    }
}
Nick
  • 1,017
  • 1
  • 10
  • 16