I have always had a huge complaint about Java’s collection classes. The complaint involves switching between types of collections. For example, let’s suppose you have an ArrayList and you want to switch it to a set. Here is how you would do it in Java.
public class CollectionConvert { public static void main(String [] args){ List lst = Arrays.asList(1, 2, 3); Set set = new HashSet(lst); } }
Ok so let’s be honest here. It’s not as if it’s really that difficult to convert a List to a Set in Java. All of the constructors of the Java collection class accept another collection so we can pass an existing collection into a new collection to handle switching between collection types.
But let’s face the fact. It can be better than this. We are using two lines of code that could be done with one piece of code instead. Here is how it’s done in Kotlin.
fun Shop.getSetOfCustomers(): Set { // Return a set containing all the customers of this shop return customers.toSet() }
Kotlin extends Java’s collection classes with these sort of conversion method. It may not seems like a big deal until you want to do something like this.
val lst = arrayListOf(1, 2, 3, 3, 4, 5, 6, 6, 7, 8, 9) //Filter out duplicates and maintain a list val noDuplicates = lst.toSet().toList() //continue working with list instead of set...
The Set interface lacks method such as get(index). Sometimes it’s helpful to remove all duplicates in a list prior before working on the list. Java 8 does a lot of help with this problem, but I still think Kotlin is more consice.
List lst = Arrays.asList(1, 1, 1, 2, 2, 2, 3, 3, 3); List noDuplicates = lst.stream().distinct().collect(Collectors.toList());
You can click here to see Part 13
One thought on “Kotlin Koans—Part 14”