HashMap java

1 분 소요

getOrDefault

key가 존재할 경우 value를 반환하고 없을 경우 defaultValue 반환

@Override
public V getOrDefault(Object key, V defaultValue) {
    Node<K,V> e;
    return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}

for 반복

for (String key : map.keySet()) {
    // ...
}
        
for (Object value : map.values()) {
    // ...
}

for (Map.Entry<String, Object> entry : map.entrySet()) {
    String key = entry.getKey();
    Object value = entry.getValue();
    // ...
}

sort

SortedSet<String> keys = new TreeSet<>(map.keySet());
for (String key : keys) { 
   String value = map.get(key);
   // Sort by Key
}

SortedSet<String> values = new TreeSet<>(map.values());
for (String value : values) {
    // Sort by Value
}

Comparator<Foo> comparator = (Foo o1, Foo o2) -> {
    // placed inline for the demonstration, but doesn't have to be a lambda expression
}
SortedSet<Foo> keys = new TreeSet<>(comparator);
keys.addAll(map.keySet());
public class SortingTest {

    private HashMap<Integer, String> map;

    @Before
    public void initVariables() {
        map = new HashMap<>();
        map.put(55, "John");
        map.put(22, "Apple");
        map.put(66, "Earl");
        map.put(77, "Pearl");
        map.put(12, "George");
        map.put(6, "Rocky");
    }

    @Test
    public void givenMap_whenSortingByKeys_thenSortedMap() {
        Integer[] sortedKeys = new Integer[]{6, 12, 22, 55, 66, 77};

        List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
        entries.sort(Comparator.comparing(Map.Entry::getKey));
        HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<Integer, String> entry : entries) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        assertTrue(Arrays.equals(sortedMap.keySet()
                .toArray(), sortedKeys));
    }

    @Test
    public void givenMap_whenSortingByValues_thenSortedMap() {
        String[] sortedValues = new String[]{"Apple", "Earl", "George", "John", "Pearl", "Rocky"};

        List<Map.Entry<Integer, String>> entries = new ArrayList<>(map.entrySet());
        entries.sort(Comparator.comparing(Map.Entry::getValue));
        HashMap<Integer, String> sortedMap = new LinkedHashMap<>();
        for (Map.Entry<Integer, String> entry : entries) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        assertTrue(Arrays.equals(sortedMap.values()
                .toArray(), sortedValues));
    }
}

댓글남기기