Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Set<Object> to Collection<String>

I have a Set<Object>.

I need to get a Collection<String> from it.

I can think of making a for loop to add and cast all the Objects, but that is ugly and probably also slow.

@Override
public Collection<String> keys()
{
    // props is based on HashMap
    Set<String> keys = new HashSet<>();
    for (Object o : props.keySet()) {
        keys.add((String) o);
    }
    return keys;
}

What is the right way?

like image 963
MightyPork Avatar asked Jul 26 '14 17:07

MightyPork


1 Answers

If you know that all the Objects inside the HashSet are strings, you can just cast it:

Collection<String> set = (Collection<String>)(Collection<?>)props.keySet();

Java implements generics with erasure, meaning that the HashSet itself doesn't know at runtime that it's a HashSet<Object>--it just knows it's a HashSet, and the compiler is responsible for helping programmers to avoid doing things that would create runtime exceptions. But if you know what you're doing, the compiler won't prevent you from doing this cast.

like image 105
StriplingWarrior Avatar answered Oct 17 '22 04:10

StriplingWarrior