Commit c7e7fbba by Patryk Czarnik

putIfAbsent

parent 4c3c32eb
......@@ -12,8 +12,8 @@ public class Grupowanie2 {
Map<String, BigDecimal> slownik = new TreeMap<>();
for(Rekord r : lista) {
BigDecimal suma = slownik.getOrDefault(r.miasto(), BigDecimal.ZERO);
slownik.put(r.miasto(), suma.add(r.wartosc()));
BigDecimal suma = slownik.getOrDefault(r.miasto(), BigDecimal.ZERO);
slownik.put(r.miasto(), suma.add(r.wartosc()));
}
for (Map.Entry<String, BigDecimal> entry : slownik.entrySet()) {
......
package sprzedaz;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
/* Operacje "funkcyjne" na słownikach dostępne od Java 8:
compute, computeIfPresent, computeIfAbsent, putIfAbsent, ...
*/
public class Grupowanie3 {
public static void main(String[] args) {
List<Rekord> lista = ObslugaCSV.wczytaj();
Map<String, BigDecimal> slownik = new TreeMap<>();
for(Rekord r : lista) {
slownik.putIfAbsent(r.miasto(), BigDecimal.ZERO);
BigDecimal suma = slownik.get(r.miasto());
slownik.put(r.miasto(), suma.add(r.wartosc()));
}
for (Map.Entry<String, BigDecimal> entry : slownik.entrySet()) {
System.out.printf("%-10s : %12s%n", entry.getKey(), entry.getValue());
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment