使用java 8流修改列表中对象的属性值 [英] Modify property value of the objects in list using java 8 streams

查看:26388
本文介绍了使用java 8流修改列表中对象的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在arraylist中有一个 Fruit 对象的列表,我想将fruitName修改为其复数名称。
参考示例:

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)]

我们是否有办法使用java8流实现相同的行为?

Do we have any way to achieve same behavior using java8 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())

如果你想修改当前列表,请使用集合.forEach

If you wanna modify current list, use Collection.forEach:

fruits.forEach(f -> f.setName(f.getName() + "s"))

这篇关于使用java 8流修改列表中对象的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆