用stream / lambda /方法引用替换常规foreach

时间:2016-07-24 02:56:38

标签: java

我有一个Class Foo,其Constructor设置为nameid

在另一个Class我有List<String>条消息,我可以提取nameid

我能够通过使用常规Constructor循环遍历列表来成功设置foreach。如何使用Stream Java 8LambdaMethod 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;
}

}

1 个答案:

答案 0 :(得分:1)

这个怎么样?

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

或者这个

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