-2

I have three hashmaps, 2 of them have multiple values (arrayLists).

Map<String, String> advise = new HashMap<String, String>();
    Map<String, ArrayList<String>> teach = new HashMap<String,ArrayList<String>>();
    Map<String, ArrayList<String>> takesCo = new HashMap<String,ArrayList<String>>();
    //ArrayList<String> courses = new ArrayList<String>; 

I want to iterate over them based on the key of the first hashmap (advise) The array lists contain course names and I want to print when there is a match.

for (String x : advise.keySet()) { 
    String y = advise.get(x);
    ArrayList<String> z1values = teach.get(y) ;
    ArrayList<String> z2values = takesCo.get(x) ;
    if (!z1values.isEmpty() && !z2values.isEmpty()){
    for (String z1:z1values){
        for (String z2:z2values){
            if (z1.equals(z2)){
                result=x+","+y+","+z1;
                system.out.println(result);
                }
            }
        }
    }
}

I get nullPointerException in line with the if statement

vinS
  • 1,417
  • 5
  • 24
  • 37
zaranaid
  • 65
  • 1
  • 13
  • have you tried debugging in your IDE? Exception Trace generated will tell you what was null and what can be done to avoid this. – Nishant Dec 18 '17 at 07:09
  • In the first if statement, you are invoking a method on a null object (z1values.isEmpty()). You need to make sure z1values is not null before invoking to determine whether the list is empty. – Zachary Dec 18 '17 at 07:10
  • "with **the** if statement" you've got two of them in this code: be specific as to the one you mean (e.g. "the first if statement"); or just omit the irrelevant code. – Andy Turner Dec 18 '17 at 08:07

1 Answers1

2

Just change your condition from

!z1values.isEmpty() && !z2values.isEmpty()

to

z1values != null && z2Values != null && !z1values.isEmpty() && !z2values.isEmpty()
Krzysztof Mazur
  • 568
  • 2
  • 13
  • wonderful answer ,quick and correct! I had tried 'z1values != null && z2Values != null' alone and '!z1values.isEmpty() && !z2values.isEmpty()' alone before but didnt work. what is the difference between the two? – zaranaid Dec 18 '17 at 07:18
  • isEmpty() checks if size of array list is 0 or not.. but if will invoke this when list is null it will throw NullPointerException. That's why before calling this you need to make sure that list is not null. – DhaRmvEEr siNgh Dec 18 '17 at 07:38
  • An alternative (at least with Java 8+, and assuming you don't insert null values intentionally) is to use `teach.getOrDefault(y, Collections.emptyList())`: then you get an empty list instead of null, so the null check is unnecessary. Then again, checking if the list is empty is also unnecessary, since you don't do anything for an empty list anyway. – Andy Turner Dec 18 '17 at 08:09