Converting Collections to different types in Java

This cannot be the most exciting thing on the internet today, but I still researched it SO MUCH this week. I had a task that involved needing to expand the scope of a function from just handling type Short to handling type Integer as well. Now, if you know anything about primitive types, these two don’t play very well (even though they should!!) so getting them to cooperate was Very Annoying. What happened is that I had a collection of shorts and needed to convert them to a collection of Integers. Now for most of the places I could just read them all as Integers, cast the few hard-coded values and be done. But there was this one place where we were using code that I’m not allowed to touch (because of stupid bureaucracy). So I had to convert one Collection of Shorts to a Collection of Integers.

You can cast an individual short into an integer, as such:

Short myShort = 60;
Integer myInt = (int) myShort;

Now this isn’t very pretty but hey it works. I wanted to do the same thing with collections, there had to be some way of telling a collection to cast it’s elements to another type in another collection… right? It felt so obvious. (Of course now I realize I was thinking of Mapping in Scala)

So I wanted this:

Set<Short> myShorts = new HashSet<>(Arrays.asList((short)12, (short)13, (short)14)); // a bit of a hack Set to prove my point
Set<Integer> myInts = new HashSet<>((int) myShorts);

But you can’t do that. Java throws a lovely little error like “nah nah nah nah you can’t get this”. I googled and googled and googled and all I found was to simply iterate through and cast them all one by one.

Now, I hear tell that Java 11 might have something that could help with this, but currently for me, I’m dealing with an old Java 8 platforms and I don’t have that luxury. I miss Scala – Scala would have made this much easier, but alas I’m stuck with bulky java and knowing that a thing could be better.

I’ll go into more about what you can do in Scala around pattern matching in a different post, but for the moment, check out this page for more info on it.

This stack overflow thread

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s