Modify property value of the objects in list using Java 8 streams
If you wanna create new list, use Stream.map
method:
List<Fruit> newList = fruits.stream()
.map(f -> new Fruit(f.getId(), f.getName() + "s", f.getCountry()))
.collect(Collectors.toList())
If you wanna modify current list, use Collection.forEach
:
fruits.forEach(f -> f.setName(f.getName() + "s"))
You can use just forEach
. No stream at all:
fruits.forEach(fruit -> fruit.setName(fruit.getName() + "s"));
You can use peek
to do that.
List<Fruit> newList = fruits.stream()
.peek(f -> f.setName(f.getName() + "s"))
.collect(Collectors.toList());