我可以在列表元素上应用一个函数,并使用java流将列表元素和函数返回值存储在键值对中吗



我有一个字符串列表

List <String> Ids = [id1, ids2, id3];

和一个功能

public List<String> getDays(String id) {
// makes api call and fetch all the days in a list where id is present
return list;
}

现在我想对ID的每个列表元素执行getDays功能,并将其存储在地图中

Map<String, List<String> where String would be my Id from List(IDs) and 
List<String> would be the corresponding return value of getDays 
function on each Id

一旦我得到了一张地图,我就可以在一周中的某一天使用它进行进一步的操作,比如过滤它或检查我的ID。

我知道这可以使用for循环来完成,但我更感兴趣的是知道是否有其他方法,如流或映射实用程序。

使用Collectors.toMap

public static void main(String[] args) {
List<String> Ids = Arrays.asList("id1", "id2", "id3");
Map<String, List<String>> result = Ids.stream().collect(Collectors.toMap(Function.identity(), MyClass::getDays));
System.out.println(result); // {id2=[id2_foo, id2_bar], id1=[id1_foo, id1_bar], id3=[id3_foo, id3_bar]}
}
/* DEMO METHOD */
public static List<String> getDays(String id) {
return Arrays.asList(id + "_foo", id + "_bar");
}

使用lambda表示法可能更容易理解

Map<String, List<String>> result = Ids.stream()
.collect(Collectors.toMap(id->id, id -> getDays(id)));

最新更新