简体   繁体   English

从映射中获取 Java 中特定键的长值列表

[英]Get a List of Long values from a Map for a specific Key in Java

I have a Map: Map<String, Object> data The content is:我有一个 Map: Map<String, Object> data内容是:

{"id_list":["2147041","2155271","2155281"],
 "remoteHost":"127.0.0.1",
 "userId":"user",
 "agencyId":1}

I want to store in a Long List, all the values with Key: id_list It would be:我想存储在一个长列表中,所有带有Key: id_list的值将是:

list:[2147041,2155271,2155281] Is there a way to do that? list:[2147041,2155271,2155281]有没有办法做到这一点? I've got:我有:

List<Long> list = new ArrayList<Long>(data.get("id_list") );

new ArrayList<Long>(Arrays.asList(data.get("id_list")));

Assuming that is an array in your hashMap. 假设这是您的hashMap中的一个数组。 Otherwise you'd have to cast it as an (Iterable<String>)data.get("id_list"); 否则,您必须将其(Iterable<String>)data.get("id_list");(Iterable<String>)data.get("id_list"); and add each String one by one. 并逐一添加每个字符串。

It looks like the values in the collection of id_list are String objects, so you should be able to do it with a loop that performs conversions: 看起来id_list集合中的值是String对象,因此您应该能够通过执行转换的循环来做到这一点:

Iterable<String> idStrings = (Iterable<String>)data.get("id_list");
List<Long> list = new ArrayList<Long>();
for (String id : idStrings) {
    list.add(Long.valueOf(id));
}

You can use Arrays.asList to instantiate from that array 您可以使用Arrays.asList从该数组实例化

List<Long> list = Arrays.asList(data.get("id_list"));

or if you want a new ArrayList instead of just a genericl List 或者如果您想要一个新的ArrayList而不是一个通用列表

List<Long> list = new ArrayList<Long>(Arrays.asList(data.get("id_list")));

If running on Java 8 or later , you may use a BiFunction for this:如果在Java 8 or later上运行,您可以为此使用BiFunction

  

  private BiFunction<Map<String, Object>, String, List<Long>> convertToLong() {
    return (thatMap, targetKey) -> thatMap.get(targetKey).stream()
          .map(id -> Long.valueOf(id))
          .collect(Collectors.toList());
  }

    // The call

    String targetKey = "id_list";
    // prepare the values of this accordingly.
    Map<String, Object> thatMap = new HashMap<>();

    List<Long> converted = convertToLong().apply(thatMap, targetKey)
    
    // Assumption for the output: your map contains the sample data provided here.
    System.out.println("converted: " + converted); //=> [2147041, 2155271, 2155281]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM