gpt4 book ai didi

Java Stream 映射到多个属性

转载 作者:行者123 更新时间:2023-12-01 23:24:03 25 4
gpt4 key购买 nike

我正在使用Optional<ObjectNode>并使用流从中提取各种属性。

class MyCompany {
private Age age;
private Name name;

// getters and setters

}

myJSON
.map(jsonObj -> getAge(jsonObj, "age"))
.map(age -> new Age(age))
.ifPresent(myCompany::setAge);


myJSON
.map(jsonObj -> getName(jsonObj, "name"))
.map(name -> new Name(name))
.ifPresent(myCompany::setName);

public Integer getAge(ObjectNode jsonObj, String toGet) {
Integer value = null;

if (jsonObj(toGet)) {

value = jsonObj(toGet).intValue();

}

return value;
}

现在我想更改 MyCompany包括一个新的Person类而不是 Person应包括姓名和年龄属性。如何在单个语句中使用 Java 流来制定 Person根据姓名和年龄,然后将其设置为 MyCompany

class Person {
private Age age;
private Name name;
// getters and setters


public void Person(Age age, Name name) {
this.name = name;
this.age = age;

}
}

class MyCompany {
private Person person;
//getters and setters for Person
}

最佳答案

没有关于 Optional<ObjectNode> 的更多信息在您的片段代码中,尝试使用以下代码。

@Test
public void test2() {

//MyCompany JSON String
String myCompany = "{\"age\":20,\"name\":\"Tom\"}";
JSONObject jsonObject = JSONObject.parseObject(myCompany);

//convert to Company with Person
Optional<Company> tom = Stream.of(jsonObject).map(m -> new Person(m.getInteger("age"), m.getString("name")))
.map(p -> new Company(p)).findFirst();
if (tom.isPresent()) {
System.out.println(tom.get());
//output in console
//Tests.Company(person=Tests.Person(age=20, name=Tom))
}
}

@Data
@AllArgsConstructor
static class Person {
private int age;
private String name;
}

@Data
@AllArgsConstructor
static class Company {
private Person person;
}

@Data
@AllArgsConstructor
static class MyCompany {
private int age;
private String name;
}

关于Java Stream 映射到多个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58313735/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com