我在 ArrayList 中有一个 Fruit
对象的列表,我想将 fruitName
修改为它的复数名称。
举个例子:
@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流来实现相同的行为吗?