我是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