Search code examples
javajava-6

Java Map compute() Example on Java 1.6


I have to work on Java 1.6. I have difficulty converting the following code running on Java 1.8.

Map<String, Double> maksimum = new HashMap<>();
List<Record> records;
for (Record record : records) {
    record.getFeatures().forEach((key, value) -> {
        maksimum.compute(key, (k1, max) -> max == null || value > max ? value : max);
    });
}

what I have transformed is as follows. I wonder where I'm doing wrong.

for(Record rec : records) {
    for (Map.Entry<String, Double> entry : rec.getFeatures().entrySet()) {
        if (entry.getKey()==null || maksimum.containsKey(entry.getKey())) {
            maksimum.replace(entry.getKey(), maksimum.get(entry.getValue()));
        }   
    }
}

Solution

  • If I understand correctly your initial code in Java 8, you want to store the maximum value for every key in your Map. Here is the code that should do that in Java 6:

    Map<String, Double> maksimum = new HashMap<String, Double>();
    
    for (Record record : records) {
        for (Map.Entry<String, Double> recordEntry : record.getFeatures().entrySet()) {
            String key = recordEntry.getKey();
            Double value = recordEntry.getValue();
    
            Double initialValue = maksimum.get(key);
            if (initialValue == null) {
                maksimum.put(key, value);
            } else {
                maksimum.put(key, Math.max(value, initialValue));
            }
        }
    }
    

    Note that the replace function that you've used in your example was introduced in Java 8. Docs: https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#replace-K-V-