Cast Object to Long using stream in java



Casting can be done using stream in java. Casting object to long directly it can't be done, so first need to cast it to string then long.

map(String :: valueOf) - casting object to string.
map(Long :: valueOf) - casting string to long.

Then collect it to list<long> using collectors.


private List<Long> getLongList(List<Object> objectList) {
if(objectList != null && ! objectList.isEmpty()) {
return objectList.stream().map(String :: valueOf).map(Long :: valueOf).collect(Collectors.toList());
}
return null;
}






Post a Comment

Previous Post Next Post