我是java 8的新手,并且有创建对象时需要进行一些检查的情况。 我当然在使用这个流,并且在完成这个过程中经历了艰难的时间。使用Java 8流处理嵌套的if/else语句
输入是一个包含键/值对的HashMap对象,输出应该在下面。
| userrole | userid | username | output |
|------------|--------|----------|----------|
| "" (blank) | 111 | amathews | 111 |
| "" | | amathews | amathews |
| Admin | 111 | amathews | 111 |
| Admin | 111 | "" | 111 |
| Admin | | amathews | Admin |
这是如何确定userid> userrole>用户名。
每个HashMap对象都将包含userrole/username/userid作为键和其值以及其他键/值对。 我们将有大量嵌套的if/else语句来完成此任务的Java之前的版本。
我们将有一堆嵌套的if/else语句来完成此前的Java版本中的任务。
这是我到目前为止的代码。
map.entrySet().stream()
.filter(e -> e.getValue() instanceof String || e.getValue() instanceof Integer)
.filter(e -> e.getKey().contains("userrole") || e.getKey().contains("userid") || e.getKey().contains("username"))
.map(e -> e.getValue())
.collect(Collectors.toList());
我知道我在流中写入map函数的方式也不正确。 如何在java 8中完成此操作?我不知道如何在这里添加嵌套的if/else部分。
请有人帮我在这里我卡住了,无法继续。谢谢。
编辑:对不起,如果我没有明确说明问题。这里是代码snippiet。
public List<UserAction> getUserActionList(Map<String, String> map)
{
String userRole = map.get("userrole");
String userName = map.get("username");
String userId = map.get("userid");
String output = null;
// if userrole, userid and username are not null/empty, then output is userid
if(!checkForNullEmpty(userRole) && !checkForNullEmpty(userId) && !checkForNullEmpty(userName))
output = userId;
// if userrole and userid are null/empty and username is not empty/null, then output is username
else if(checkForNullEmpty(userRole) && checkForNullEmpty(userId) && !checkForNullEmpty(userName))
output = userName;
// if userid and username are null/empty and userrole is not empty/null, then output is userrole
else if(!checkForNullEmpty(userRole) && checkForNullEmpty(userId) && checkForNullEmpty(userName))
output = userRole;
List<UserAction> udList = new ArrayList<>();
// Add the map and output into a UserAction object
udList.add(new UserAction(map, output));
return udList;
}
我已经在这里按照表格处理了三个条件。所以这必须重构为使用Java 8流。希望现在有意义。
什么是你的实际问题?您发布的代码是否无效?如果不是,为什么不呢?如果它确实有效,你究竟在问什么?也许发布一些带有示例数据的可执行代码以及期望的数据类型应该是什么 – Bohemian
感谢您的回复。我已经添加了片段,希望现在清楚。 – 15R6
它是否保证至少有一个值会在地图中找到? – Bohemian