2016-07-24 13 views
0

我有一個ClassFoo有一個Constructor設置nameid。我可以提取nameid用流/ lambda /方法引用替換常規的foreach

我可以通過使用常規的foreach循環循環遍歷列表來成功設置Constructor。如何做到這一點使用StreamJava 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類:

​​

回答

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)))) 
+0

我做了'userList.stream()平行()地圖(用戶 - >新富(的getName(用戶)的getId(用戶)))。的forEach( fooList ::加); \t \t fooList.forEach(user - > System.out.println(user.getName()+「」+ user.getId())); '我得到空指針異常 –

+0

@ user1629109不要添加到具有並行流的列表。 – michaelsnowden

+0

這是爲什麼?任何特定的原因?有時它有效,有時它返回「NPE」 –