Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.Long cannot be cast to java.lang.String in Java

Tags:

java

casting

I'm getting response in this manner:

[{Id=1066276530, Key1=1815401000238}, {Id=1059632250, Key1=1815401000244}]

When I iterate and convert the values into a string, it throws me the error:

java.lang.Long cannot be cast to java.lang.String in Java

 for (Map<String, String> map : leadIds) {
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String applicationNumber = (String) entry.getValue();
        }
}

I want to convert the value into a string. Is there any issue here?

like image 600
Syed Avatar asked Jun 26 '15 06:06

Syed


2 Answers

Use String.valueOf() instead of casting:

for (Map<String, Long> map : leadIds) {
        for (Map.Entry<String, Long> entry : map.entrySet()) {
            String applicationNumber = String.valueOf(entry.getValue());
        }
}
like image 77
codeaholicguy Avatar answered Sep 28 '22 05:09

codeaholicguy


Because String and Long are completely different types you cannot cast them, but you can use static method String.valueOf(Long value) and backwards Long.valueOf(String value).

like image 29
Ihor Patsian Avatar answered Sep 28 '22 05:09

Ihor Patsian