【问题标题】:Can I apply a function on my list elements and store the list element and function return value in a key-value pair like a map using java streams?我可以在我的列表元素上应用一个函数,并将列表元素和函数返回值存储在一个键值对中,比如使用 java 流的映射吗?
【发布时间】:2020-11-13 19:43:34
【问题描述】:

我有一个字符串列表

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

获得地图后,我可以将其用于进一步的操作,例如过滤地图或检查我在一周中某一天的身份。

我知道可以使用 for 循环来完成,但我更想知道是否还有其他方法,例如流或地图实用程序。

【问题讨论】:

    标签: java collections java-stream


    【解决方案1】:

    使用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)));
    

    【讨论】:

      猜你喜欢
      • 2017-11-23
      • 1970-01-01
      • 2022-11-13
      • 1970-01-01
      • 2020-07-24
      • 2016-06-21
      • 2010-10-04
      • 1970-01-01
      • 2015-05-07
      相关资源
      最近更新 更多