How does Java 8 add custom elements to a collection?
•
Java
Is there a Java 8 mode to perform the following operations?
for(int i;i<=100;i++){ Person person=new Person(); person.setId(i); person.setName("name"+i); list.add(person) }
Solution
Yes:
IntStream.rangeClosed(0,100) .forEach(i -> { Person person=new Person(); person.setId(i); person.setName("name"+i); list.add(person); });
Edit:
As described below, accessing the existing list within the lambda expression parameters of a stream operation is the opposite of functional programming This is best done:
List<Person> persons = IntStream.rangeClosed(0,100) .mapToObj(i -> { Person person=new Person(); person.setId(i); person.setName("name" + i); return person; }) .collect(Collectors.toList());
see https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html.
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码