Optional<Set<String>> typeOptional = Optional.empty(); switch (type) { case "change": typeOptional = Optional.of(change); break; case "call": typeOptional = Optional.of(call); break; case "help": typeOptional = Optional.of(help); break; default: break; } //如果是true,就添加,如果是false,就删除 typeOptional.ifPresent(set -> { if (signal) { set.add(uniqueId); } else { if(set.contains(uniqueId)){ set.remove(uniqueId); } } });提炼出公共方法
时间: 2023-06-23 09:08:27 浏览: 54
可以将上述代码提取为一个公共方法如下:
```
public void addToSetOrRemoveFromSet(String type, Set<String> set, String uniqueId, boolean signal) {
Optional<Set<String>> typeOptional = Optional.empty();
switch (type) {
case "change":
typeOptional = Optional.of(change);
break;
case "call":
typeOptional = Optional.of(call);
break;
case "help":
typeOptional = Optional.of(help);
break;
default:
break;
}
typeOptional.ifPresent(typeSet -> {
if (signal) {
typeSet.add(uniqueId);
} else {
if (typeSet.contains(uniqueId)) {
typeSet.remove(uniqueId);
}
}
});
}
```
这个方法接受四个参数,分别是 `type` 表示类型,`set` 表示要操作的集合,`uniqueId` 表示要添加或删除的元素,`signal` 表示添加或删除操作。可以根据具体的业务需求调用这个方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![repositories](https://img-home.csdnimg.cn/images/20210720083646.png)