Reputation: 1356
I have a Map: Map<String, Object> data
The content is:
{"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:
list:[2147041,2155271,2155281]
Is there a way to do that?
I've got:
List<Long> list = new ArrayList<Long>(data.get("id_list") );
Upvotes: 1
Views: 2116
Reputation: 1158
If running on Java 8 or later
, you may use a BiFunction
for this:
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]
Upvotes: 0
Reputation: 817
new ArrayList<Long>(Arrays.asList(data.get("id_list")));
Assuming that is an array in your hashMap. Otherwise you'd have to cast it as an (Iterable<String>)data.get("id_list");
and add each String one by one.
Upvotes: 3
Reputation: 11
You can use Arrays.asList
to instantiate from that array
List<Long> list = Arrays.asList(data.get("id_list"));
or if you want a new ArrayList instead of just a genericl List
List<Long> list = new ArrayList<Long>(Arrays.asList(data.get("id_list")));
Upvotes: 0
Reputation: 726479
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:
Iterable<String> idStrings = (Iterable<String>)data.get("id_list");
List<Long> list = new ArrayList<Long>();
for (String id : idStrings) {
list.add(Long.valueOf(id));
}
Upvotes: 4