【问题标题】:Java Switch/Case alternative to update a Map更新地图的 Java Switch/Case 替代方案
【发布时间】:2021-04-20 02:47:22
【问题描述】:

我正在尝试找出是否有更好、更简洁的方法来实现以下代码并替换 switch/case 语句。感谢您的帮助和 cmets。

class Student {

    public String name;
    public Map<String, String> properties;

}

class MainClass {

    public void doAction(List<Student> students) {

        for (Student student : students) {

            switch (student.name) {
            case "Bob":
                student.properties.put("key1", "value1");
                student.properties.put("key2", "value2");
                break;

            case "Sophie":
                student.properties.put("key3", "value3");
                student.properties.put("key4", "value4");
                break;

            case "Natalie":
                student.properties.put("key5", "value5");
                student.properties.put("key6", "value6");
                break;
            }
        }

    }

}

【问题讨论】:

  • switch 有什么不好?
  • 没什么不好...,只是想知道是否有更好/更清洁的方法。
  • 这整件事很奇怪。如果您要创建学生列表,只需使用 Map.of() 初始化它们,不要将初始化分成不同的组件,否则会不同步且难以阅读。
  • 不,这不是初始化学生列表。我得到一个学生列表(他们的属性映射中已经有一些值),我将根据他们的名字(案例条件)添加一些属性

标签: java loops if-statement optimization switch-statement


【解决方案1】:

这样的事情怎么样?

Map<String, Map<String, String>> studentProperties = new HashMap();
studentProperties.put("Bob", Map.of("key1", "value1", "key2", "value2"));
studentProperties.put("Sophie", Map.of("key3", "value3", "key4", "value4"));
...

for (Student student : students) {
    if(studentProperties.containsKey(student.name)) {
        student.properties.putAll(studentProperties.get(student.name))
    }
}

只是因为要求是避免切换。请注意,我们通过预先填充所有条目来牺牲空间复杂度。

【讨论】:

    猜你喜欢
    • 2010-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2013-04-02
    相关资源
    最近更新 更多