Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Refer the example:

@Data @AllArgsConstructor @ToString class Fruit {      long id;     String name;     String country; }  List<Fruit> fruits = Lists.newArrayList(); fruits.add(new Fruit(1L, "Apple", "India")); fruits.add(new Fruit(2L, "Pineapple", "India")); fruits.add(new Fruit(3L, "Kiwi", "New Zealand"));  Comparator<Option> byNameComparator = (e1, e2) -> e1.getName().compareToIgnoreCase(e2.getName());  fruits = fruits.stream().filter(fruit -> "India".equals(fruit.getCountry()))             .sorted(byNameComparator).collect(Collectors.toList());  List<Fruit> fruitsWithPluralNames = Lists.newArrayList(); for (Fruit fruit : fruits) {     fruit.setName(fruit.getName() + "s");     fruitsWithPluralNames.add(fruit); }  System.out.println(fruitsWithPluralNames);  // which prints [Fruit(id=1, name=Apples, country=India), Fruit(id=2, name=Pineapples, country=India), Fruit(id=3, name=Kiwis, country=New Zealand)] 


Do we have any way to achieve same behavior using Java 8 streams ?

like image 985
Bhavesh Dangi Avatar asked Jul 21 '16 06:07

Bhavesh Dangi


People also ask

Does stream filter modify the original list?

That means list. stream(). filter(i -> i >= 3); does not change original list. All stream operations are non-interfering (none of them modify the data source), as long as the parameters that you give to them are non-interfering too.

How do you convert a list of objects into a stream of objects?

Using List. stream() method: Java List interface provides stream() method which returns a sequential Stream with this collection as its source. Algorithm: Get the Stream.


1 Answers

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")) 
like image 188
Sergii Lagutin Avatar answered Sep 17 '22 18:09

Sergii Lagutin