0
我有一個Class
Foo
有一個Constructor
設置name
和id
。我可以提取name
和id
。用流/ lambda /方法引用替換常規的foreach
我可以通過使用常規的foreach
循環循環遍歷列表來成功設置Constructor
。如何做到這一點使用Stream
Java 8
或Lambda
或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類:
我做了'userList.stream()平行()地圖(用戶 - >新富(的getName(用戶)的getId(用戶)))。的forEach( fooList ::加); \t \t fooList.forEach(user - > System.out.println(user.getName()+「」+ user.getId())); '我得到空指針異常 –
@ user1629109不要添加到具有並行流的列表。 – michaelsnowden
這是爲什麼?任何特定的原因?有時它有效,有時它返回「NPE」 –