I have a list of Fruit objects in ArrayList and I want to modify fruitName to its plural name.
Refer the example:
@Data
@Al
just for modifying certain property from object collection you could directly use forEach with a collection as follows
collection.forEach(c -> c.setXyz(c.getXyz + "a"))
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 do it using streams map function like below, get result in new stream for further processing.
Stream<Fruit> newFruits = fruits.stream().map(fruit -> {fruit.name+="s"; return fruit;});
newFruits.forEach(fruit->{
System.out.println(fruit.name);
});
You can use peek to do that.
List<Fruit> newList = fruits.stream()
.peek(f -> f.setName(f.getName() + "s"))
.collect(Collectors.toList());