我有一个方法可以接受List<String>
并List<Map<String, Object>>
:
public List<Map<String, Object>> filterMethod() {
List<String> listId = this.getUserIds(); //includes only the user id's
List<Map<String, Object>> listUser = this.getUserDetails(); // includes user_id, user_name, and user_email
List<Map<String, Object>> filteredListUser = null;
return filteredListUser;
}
我希望能够做的是比较这两者并返回一个新的List<Map<String, Object>>
。
我想做的比较作为示例显示:
比方说:
List<String> listId =
[
"8000",
"8002",
"8004",
"8006",
"8010",
"8012",
"8014",
"8016",
"8018",
"8020",
"8022",
"8024"
]
List<Map<String, Object>> listUser =
[
{
"USER_ID": "8001",
"USER_NAME": "username1",
"USER_MAIL": "email1@foo.com"
},
{
"USER_ID": "8002",
"USER_NAME": "username2",
"USER_MAIL": "email2@foo.com"
},
{
"USER_ID": "8003",
"USER_NAME": "username3",
"USER_MAIL": "email3@foo.com"
},
{
"USER_ID": "8004",
"USER_NAME": "username4",
"USER_MAIL": "email4@foo.com"
},
{
"USER_ID": "8005",
"USER_NAME": "username5",
"USER_MAIL": "email5@foo.com"
},
{
"USER_ID": "8006",
"USER_NAME": "username6",
"USER_MAIL": "email6@foo.com"
},
{
"USER_ID": "8007",
"USER_NAME": "username7",
"USER_MAIL": "email7@foo.com"
}
]
我想返回一个新的过滤List<Map<String, Object>>
,其中包含listUser USER_ID
在listId
中的listUser
行(即:(
List<Map<String, Object>> filteredListUser =
[
{
"USER_ID": "8002",
"USER_NAME": "username2",
"USER_MAIL": "email2@foo.com"
},
{
"USER_ID": "8004",
"USER_NAME": "username4",
"USER_MAIL": "email4@foo.com"
},
{
"USER_ID": "8006",
"USER_NAME": "username6",
"USER_MAIL": "email6@foo.com"
}
]
当我需要将listUser
user_id
与listId
进行比较以检查是否需要将行添加到filteredListUser
时,问题就来了。
如果这只是两个字符串数组,我会知道如何做到这一点:
String[] a = {1, 2, 3, 4, 5, 6, 7};
String[] b = {2, 4, 6, 8, 10};
ArrayList<String> c = new ArrayList<String>();
for (int i = 0; i < a.length; i++) {
if (Arrays.asList(b).contains(a[i])) {
c.add(a[i]);
}
}
我认为 for 循环也适用于列表比较,但我不确定如何将listUser
中的user_id
与List<Map<String, Object>>
和List<String>
中的listId
进行比较。
作为一个尝试和伪代码的角度来看,我试图实现的是:
public List<Map<String, Object>> filterMethod() {
List<String> listId = this.getUserIds(); //includes only the user id's
List<Map<String, Object>> listUser = this.getUserDetails(); // includes user_id, user_name, and user_email
List<Map<String, Object>> filteredListUser = null;
for (int i = 0; i < listUser.length; i++) {
if (listId.contains(listUser.USER_ID[i])) {
filteredListUser.add(listUser[i]);
}
}
return filteredListUser;
}
我不完全确定从这里去哪里 - 将不胜感激任何帮助!
抱歉,如果这是一个非常基本的问题 - 我对编程很陌生。提前谢谢你!
我会迭代List<Map<String, Object>>
并检查相应的值,以USER_ID
List<String> listId
中存在。 以下是使用 Java-8 流的方法
List<Map<String, Object>> result = listUser.stream()
.filter(m-> listId.contains(m.get("USER_ID")))
.collect(Collectors.toList());
或通过使用简单的 for 循环
List<Map<String, Object>> filteredListUser = new ArrayList<>();
for(Map<String, Object> m : listUser) {
if(listId.contains(m.get("USER_ID"))) {
filteredListUser.add(m);
}
}
您也可以使用removeIf
执行此操作,但这会修改现有地图
listUser.removeIf(m->!listId.contains(m.get("USER_ID")));