GreenHelix
GreenHelix

Reputation: 51

(Java ->Kotlin) How can I convert this code?(Stream, filter)

I have a problem of Java --> Kotlin converting.. How can I convert this code?

String[] allLongestStrings(String[] inputArray) {

    int mL = 0 ; 

    for(int i =0; i < inputArray.length; i++){

        if(mL<inputArray[i].length())
            mL = inputArray[i].length();
    }

    final int longest = mL;

    return Stream.of(inputArray)
        .filter(s -> s.length()==longest)
        .toArray(String[]:: new);    
}

I especially want to change this part.

return Stream.of(inputArray)
        .filter(s -> s.length()==longest)
        .toArray(String[]:: new); 

please help.

Upvotes: 0

Views: 232

Answers (3)

Demigod
Demigod

Reputation: 5635

I would suggest to make it this simple:

fun allLongestStrings(inputArray: Array<String>): Array<String> {
    val longest = inputArray.maxBy { it.length }?.length
    return inputArray.filter { it.length == longest }.toTypedArray()
}

Upvotes: 3

szefuf
szefuf

Reputation: 520

Have you tried IntelliJ automatic feature?

It would probably be something like:

    internal fun allLongestStrings(inputArray: Array<String>): Array<String> {

        var mL = 0

        for (i in inputArray.indices) {

            if (mL < inputArray[i].length)
                mL = inputArray[i].length
        }

        val longest = mL

        return inputArray.filter { s -> s.length == longest }.toTypedArray()

    }

Upvotes: 0

chakwok
chakwok

Reputation: 1040

    var mL = 0;

    val inputArray = Array<String>();
    for (i in 0 until inputArray.size) {
        if (mL < inputArray[i].length)
            mL = inputArray[i].length
    }

    val longest: Int = mL
    inputArray.filter {
        it.length == longest
    }

Java vs. Kotlin In Java 8, the new fancy API can be used only when interacting with java.util.stream.Stream instances.

The good thing is that all standard collections – anything that implements java.util.Collection – have a particular method stream() that can produce a Stream instance.

It's important to remember that the Stream is not a Collection. It does not implement java.util.Collection and it does not implement any of the normal semantics of Collections in Java. It is more akin to a one-time Iterator in that it is derived from a Collection and is used to work through it, performing operations on each element that is seen.

In Kotlin, all collection types already support these operations without needing to convert them first. A conversion is only needed if the collection semantics are wrong – e.g., a Set has unique elements but is unordered.

One benefit of this is that there's no need for an initial conversion from a Collection into a Stream, and no need for a final conversion from a Stream back into a collection – using the collect() calls.

Reference

Upvotes: 0

Related Questions