Iterate from 0 to n - 1
for ( int i = 0 ; i < n ; i ++ ) { if ( hashmap . containsKey ( arr . get ( i ) ) ) { hashmap . get ( arr . get ( i ) ) . add ( i ) ; } else { hashmap . put ( arr . get ( i ) , new ArrayList < Integer > ( ) ) ; hashmap . get ( arr . get ( i ) ) . add ( i ) ; } }