翻阅古今
不使用Map。它不会为您提供与您相同的编译时安全性switch。如果您仍然想摆脱它,那么我建议使用enum:public enum DataCreationStrategy { ONE("one", DataCreator::createDataOneV1, DataCreator::createDataOneV2), TWO("two", DataCreator::createDataTwoV1, DataCreator::createDataTwoV2) // ... other cases ; private final String key; private final Function<DataCreator, String> creator; private final Function<DataCreator, String> defaultCreator; DataCreationStrategy(String key, Function<DataCreator, String> creator, Function<DataCreator, String> defaultCreator) { this.key = key; this.creator = creator; this.defaultCreator = defaultCreator; } public static Function<DataCreator, String> of(String key, boolean flag) { for (DataCreationStrategy strategy: values()){ if(strategy.key.equals(key)){ return flag ? strategy.creator : strategy.defaultCreator; } } return DataCreator::createDefaultData; }}然后像这样使用它:String createdData = DataCreationStrategy.of(key, versionFlag).apply(creator);(可以替换String成你实际需要生成的数据类型)该of方法也可以以 Stream API 方式实现。但在这种特殊情况下,普通的旧 for 循环要干净得多。public static Function<DataCreator, String> of(String key, boolean flag) { return Arrays.stream(values()) .filter(s -> s.key.equals(key)) .findAny() .map(s -> flag ? flag ? s.creator : s.defaultCreator ) .orElse(DataCreator::createDefaultData);}