3 ms·
Let's say we have a list of strings and want to filter for those starting with "a". In Kotlin, we can use an extension function defined on the standard Java Arr
by ptx 5y ago
Let's say we have a list of strings and want to filter for those starting with "a". In Kotlin, we can use an extension function defined on the standard Java ArrayList object:
myStringList.filter { it.startsWith("a") }
...and on arrays:
myStringArray.filter { it.startsWith("a") }
...and on, for example, a boolean array (a standard JVM primitive array object):
myBooleanArray.filter { it != false }
This works for any kind of array and any kind of list, etc., even though the objects are ordinary JVM arrays and lists.
In Java, because it lacks extension functions, the stream functions are often not accessible from the object itself, so you have to hunt for where they've decided to put them for this particular type.
In the first case, we do have a stream method on the list:
myStringList.stream().filter(s -> s.startsWith("a")).toList();
But in the case of arrays, we have to hunt down a static method in the Arrays class:
Arrays.stream(myStringArray).filter(s -> s.startsWith("a")).toArray();
And in the last case, with a boolean array, that method doesn't work and the solution I've seen suggested is this wonderful mess (involving a different static method on a different class):
IntStream.range(0, myBooleanArray.length).mapToObj(i -> myBooleanArray[i]).filter(b -> b != false).toArray();