使用 Java 8 流修改列表中对象的属性值 [英] Modify property value of the objects in list using Java 8 streams
本文介绍了使用 Java 8 流修改列表中对象的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 ArrayList 中有一个 Fruit
对象列表,我想将 fruitName
修改为其复数名称.
I have a list of Fruit
objects in ArrayList and I want to modify fruitName
to its plural name.
参考例子:
@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)]
我们有什么方法可以使用 Java 8 流实现相同的行为吗?
Do we have any way to achieve same behavior using Java 8 streams ?
推荐答案
如果要创建新列表,请使用 Stream.map
方法:
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())
如果要修改当前列表,请使用 Collection.forEach
:
If you wanna modify current list, use Collection.forEach
:
fruits.forEach(f -> f.setName(f.getName() + "s"))
这篇关于使用 Java 8 流修改列表中对象的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文