/** * Increments the value of an existing key by 1. * If the key doesn't exist, initialises the value to 1. * * @param key The key to increment or insert. */ public void upsert(final String key) { upsert(key, 1L); } }
public FreqMap(final String initialKey) { super(); upsert(initialKey); }
@Before public void initFreqMap() { this.freqMap = new FreqMap(); freqMap.upsert("cat"); freqMap.upsert("cat"); freqMap.upsert("dog"); freqMap.upsert("cow"); freqMap.upsert("cow"); freqMap.upsert("catdog"); freqMap.upsert("catdog"); freqMap.upsert("catdog"); freqMap.upsert("cat"); freqMap.upsert("cat"); }
/** * Creates a filtered copy of the map using a supplied predicate.<br> * Returns a copy of the map if predicate supplied is null. * * @param map The frequency map that is to be sorted through * @return A new frequency map with only the filtered entries present. */ private FreqMap filterPredicate(final FreqMap map) { final FreqMap f = new FreqMap(); if (predicate == null) { map.forEach(f::upsert); } else { map.entrySet().stream().filter(e -> predicate.test(e.getKey())) .forEach(e -> f.upsert(e.getKey(), e.getValue())); } return f; }
@Test public void testUpsertUpdatesExistingKeyValue() { //given final String key = "test"; final Long initialValue = 3L; final Long increment = 11L; final Long expected = 14L; freqMap.put(key, initialValue); //when freqMap.upsert(key, increment); //then assertEquals(freqMap.get(key), expected); }
@Test public void testUpsertCreatesNewKeyValue() { //given final String key = "test"; final Long value = 6L; //when freqMap.upsert(key, value); //then assertTrue(freqMap.containsKey(key)); assertEquals(value, freqMap.get(key)); }
@Test public void testUpsertOverloadedCreateDefaultValue() { //given final String key = "test"; final Long expected = 1L; //when freqMap.upsert(key); //then assertTrue(freqMap.containsKey(key)); assertEquals(freqMap.get(key), expected); }
/** * Increments the value of an existing key by 1. * If the key doesn't exist, initialises the value to 1. * * @param key The key to increment or insert. */ public void upsert(final String key) { upsert(key, 1L); } }
private FreqMap getVehicleCounts(final String[] fields) { final FreqMap freqMap = new FreqMap(); for (final RoadTrafficDataField fieldName : RoadTrafficDataField.VEHICLE_COUNTS) { Long value; try { value = Long.parseLong(fields[fieldName.ordinal()]); } catch (final ArrayIndexOutOfBoundsException e) { value = 0L; } freqMap.upsert(fieldName.name(), value); } return freqMap; }
private FreqMap getVehicleCounts(final CSVRecord record) { final FreqMap freqMap = new FreqMap(); for (final RoadTrafficDataField field : RoadTrafficDataField.VEHICLE_COUNTS) { final String value = record.get(field.fieldName()); freqMap.upsert(field.name(), value.isEmpty() ? 0 : Long.parseLong(value)); } return freqMap; } }