Java嵌套集合增删操作

public class CollectionTest {

    // k-姓名,v-去过的地点
    private final Map> map = new HashMap<>(64);

    public void test() {
        save("小明", "大连");
        save("小明", "吉林");
        save("小张", "海南");

        System.out.println(map);
    }

    public static void main(String[] args) {
        CollectionTest test = new CollectionTest();
        test.test();
    }

    public void save(String name, String place) {
        Set places = map.computeIfAbsent(name, k -> {
            Set set = new HashSet<>();
            set.add("北京");
            return set;
        });

        places.removeIf(item -> Objects.equals(item, "北京"));

        places.add(place);
        map.put(name, places);
    }

    public void save2(String name, String place) {
        Set places = map.getOrDefault(name, new HashSet<>());
        places.add(place);
        map.put(name, places);
    }
}

参考:【【优雅代码】java嵌套集合的增删操作】 https://www.bilibili.com/video/BV1E84y1z7rn/?share_source=copy_web&vd_source=bc2f80974f681573288a3f39db28806a

你可能感兴趣的:(java)