在map()方法中使用lambda表达式使用三元运算符时,Java8 Stream()会抛出错误

问题描述 投票:0回答:1
package chap_10;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 손님 이름 및 나이 정보를 위한 Customer 클래스 생성
 * 입장료는 1인당 5000원 고정
 * 20세 이상의 손님들에게만 입장료 부과( 그 외에는 무료 )
 */
public class _Quiz_10 {
    public static void main(String[] args) {
        List<Customer> customerList = new ArrayList<>();

        customerList.add(new Customer("챈들러",50));
        customerList.add(new Customer("레이첼", 42));
        customerList.add(new Customer("모니카", 21));
        customerList.add(new Customer("벤자민", 18));
        customerList.add(new Customer("제임스", 5));

        System.out.println("미술관 입장료");
        System.out.println("==================");

        customerList.stream()
                .map(x->x.getAge()>=20 ? x.setName(x.getName() + " 5000원"):x.setName(x.getName()+ " 무료")) // error
                .forEach(System.out::println);

    }
}

class Customer{
    private String name;
    private int age;

    public Customer(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }



    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

通过在map()函数中使用条件运算符,如果年龄为20岁或以上,则将“5000 won”附加到字符串末尾,否则尝试“free”,但会发生错误。

Customer类中,setter和getter用于使用三元运算符比较值,如果为true,则使用setName()插入新字符串,但出现以下错误。 enter image description here

java dictionary stream
1个回答
0
投票

当您想要更改流的每个值时,请使用

map
。这意味着您放入
map
中的 lambda 必须具有返回类型。然而,就您而言,
setName
最有可能是
void
函数。

因此,当您想要产生副作用(例如改变属性)时,使用

map

 不是正确的函数。您可以使用 
.peek
 方法来代替,但在您的情况下,我宁愿只使用普通的 for 循环。当您只进行副作用操作时,流并不是真正的工作工具。

偷看:

customerList.stream() .peek(x -> x.getAge() >= 20 ? x.setName(x.getName() + " 5000원") : x.setName(x.getName() + " 무료")) .forEach(System.out::println);
使用 for 循环:

for (var customer : customerList) { var newName = customer.getAge() >= 20 ? customer.getName() + " 5000원" : customer.getName() + " 무료"; customer.setName(newName); System.out.println(customer); }
    
© www.soinside.com 2019 - 2024. All rights reserved.