Search code examples
javahashmaplinkedhashmap

Suspicious call to 'LinkedHashMap.get'


Hello I have the following code

public static LinkedHashMap<Object, String[]> dataMap = new LinkedHashMap<>();

public static void parseDataset(int line){
  String[] dataArr = dataMap.get(dataMap.keySet().toArray()[line]);
}

Since the Object I use as a Key is dynamically generated I have no knowledge about it so I have to find it before I can use it to get its value.

This code gives me the warning Suspicious call to 'LinkedHashMap.get', is that a problem and how would I get rid of the warning?


Solution

  • You don't need to use get: instead of converting the keys to an array, use values() instead. This works because values() iterates in the same order as the corresponding keys():

    String[] dataArr = (String[]) dataMap.values().toArray()[line];
    

    But you don't need to use toArray() either, which wastefully allocates an array containing all values, from which you only want one: you can just iterate through the values to get the thing you want:

    static String[] nthItem(int n) {
      int i = 0;
      for (String[] value : dataMap.values()) {
        if (i == n) return value;
        ++i;
      }
      throw new ArrayIndexOutOfBoundsException();
    }
    

    Or:

    String[] dataArr = dataMap.values().stream().skip(line).findFirst().orElseThrow();
    

    (Existing implementations of this sort of thing can be found in commonly-used libraries, e.g. Guava's Iterables.get)