Syed
Syed

Reputation: 2607

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

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?

Upvotes: 23

Views: 76571

Answers (2)

codeaholicguy
codeaholicguy

Reputation: 1691

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());
        }
}

Upvotes: 21

Ihor Patsian
Ihor Patsian

Reputation: 1298

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).

Upvotes: 5

Related Questions