user1629109 user1629109 - 4 months ago 9
Java Question

Replace the regular foreach with stream/lambda/method references

I have a

Class
Foo
that has a
Constructor
that sets
name
and
id
.

In another
Class
I have a
List<String>
of messages where I can extract the
name
and
id
.

I'm able to successfully set the
Constructor
by looping through the list using regular
foreach
loop. How do I achieve this using
Stream
Java 8
or
Lambda
or
Method References


public class ConstructorTest {

public static void main(String[] args) {
List<Foo> fooList = new ArrayList<Foo>();
List<String> userList = new ArrayList<String>();
userList.add("username1_id1");
userList.add("username2_id2");
//I want to replace the below foreach loop with stream/lambda/methodreferences
for (String user : userList) {
Foo foo = new Foo(getName(user), getId(user));
fooList.add(foo);
}
}

private static String getName(String user) {
return user.split("_")[0];
}

private static String getId(String user) {
return user.split("_")[1];
}
}


Foo Class:

public class Foo {

public Foo(String name, String id) {
this.name = name;
this.id = id;
}

private String name;
private String id;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

}

Answer

How about this?

userList.stream().map(user -> new Foo(getName(user), getId(user)).forEach(userList::add)

Or this

userList.forEach(user -> userList.add(new Foo(getName(user), getId(user))))
Comments