How to convert this java code: collect(ArrayList::new, ArrayList::add, ArrayList::addAll);


#1

Hi folks,
Do you have any idea to convert the following java code to kotlin? I have trouble in convert this line:
List list = u.roles.stream().map(role -> role.permissions).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);


import java.util.ArrayList;
import java.util.List;

public class Mytest {
public void test() {
User u = new User();
List<String> list = u.roles.stream().map(role -> role.permissions).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
list.forEach(System.out::println);
}

public static void main(String[] args) {
    Mytest mytest = new Mytest();
    mytest.test();
}

}

class User {
List<Role> roles = new ArrayList<>();
}

class Role {
List<String> permissions = new ArrayList<String>();
}

updated the code above.


#2

Maybe you want this?

u.roles.map { it.permissions }.toList()


#3

I’m a newbie in Kotlin, but is what you’re asking similar to .NET’s “SelectMany”?

class User(val name:String, val roles:Sequence)
class Role(val permissions:Sequence)
class Permission(val theData:Int)

fun main() {
val p1 = Permission(1)
val p2 = Permission(2)
val p3 = Permission(3)
val p4 = Permission(4)
val p5 = Permission(5)
val p6 = Permission(6)
val p7 = Permission(7)
val p8 = Permission(8)

val r1 = Role(sequenceOf(p1,p2))
val r2 = Role(sequenceOf(p3,p4))
val r3 = Role(sequenceOf(p5,p6))
val r4 = Role(sequenceOf(p7,p8))

val u1 = User("User1", sequenceOf(r1,r2))
val u2 = User("User2", sequenceOf(r3,r4))

val users = sequenceOf(u1,u2)

users.map { Pair<String, Sequence<Int>>(it.name, it.roles.flatMap { it.permissions.map { it.theData } }) }
        .forEach { println("${it.first} has permission ${it.second.map { it }.toList()}") }

}

And the output is like this:
User1 has permission [1, 2, 3, 4]
User2 has permission [5, 6, 7, 8]


#4

Kotlin exercises is a good starting point :wink:


#5

I mean, I’m a noob trying to help the guy posting the question :slight_smile:


#6

No, this isn’t what I want. Because the returned list is a list of array instead of string.

The list in java supposed to be this:
list: { stringA, stringB,stringC}

but u.roles.map { it.permissions }.toList():
the list could be {[stringA,stringB],[stringC]}


#7

I’m not sure whether this is a recommended way to meet my requirement


#8

Use flatMap instead if you want it to be [ stringA, stringB, stringC ]

u.rolese.flatMap { it.permissions }.toList()