Modify property value of the objects in list using Java 8 streams

前端 未结 5 1764
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-08 04:26

I have a list of Fruit objects in ArrayList and I want to modify fruitName to its plural name.

Refer the example:

@Data
@Al         


        
相关标签:
5条回答
  • 2020-12-08 04:43

    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"))
    
    0 讨论(0)
  • 2020-12-08 04:54

    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"))
    
    0 讨论(0)
  • 2020-12-08 04:54

    You can use just forEach. No stream at all:

    fruits.forEach(fruit -> fruit.setName(fruit.getName() + "s"));
    
    0 讨论(0)
  • 2020-12-08 04:55

    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);
            });
    
    0 讨论(0)
  • 2020-12-08 04:58

    You can use peek to do that.

    List<Fruit> newList = fruits.stream()
        .peek(f -> f.setName(f.getName() + "s"))
        .collect(Collectors.toList());
    
    0 讨论(0)
提交回复
热议问题