Java: 根据数组大小设置不同的对象字段

Java: Set Different Object Fields Based On Array Size

我有一个包含以下字段的对象:

@Data
public class Person {
    private String code1;
    private String code2;
    private String code3;
    private String code4;
};

然后我需要根据输入数组大小设置那些代码字段:

 if array has size 1, set code1
 if array has size 2, set code1, code2
 if array has size 3, set code1, code2, code3
 if array has size 4, set code1, code2, code3, code4

我用了 4 个 if 块。有没有办法在循环中执行此操作,以便在要添加更多代码字段时,我不需要继续添加 if 块?谢谢。

为了避免 if,您可以首先通过 lambda 或方法引用创建 setter 调用的集合,然后根据数据量对其进行迭代。

public class Demo {
    static List<BiConsumer<Person,String>> personSetters = List.of(
        (p, s) -> p.setCode1(s), //OR Person::setCode1,
        (p, s) -> p.setCode2(s), //OR Person::setCode2,
        (p, s) -> p.setCode3(s), //OR Person::setCode3,
        (p, s) -> p.setCode4(s)  //OR Person::setCode4
    );

    static Person createPersonFrom(String[] data){
        Person person = new Person();
        for (int i = 0; i<data.length; i++){
            personSetters.get(i).accept(person, data[i]);
        }
        return person;
    }

    public static void main(String[] args) throws Exception {
        String[] data = {"val1","val2"};
        System.out.println(createPersonFrom(data));
    }
}

输出:Person{code1='val1', code2='val2', code3='null', code4='null'}