동일한 구조의 중첩 된 POJO로 읽는 아래 Json이 있습니다.
{
"employees": [
{
"name": "John",
"age": "30",
"proData": [
{
"year": "1",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
},
{
"year": "2",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
},
{
"year": "3",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
}
]
},
{
"name": "Scott",
"age": "32",
"proData": [
{
"year": "1",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
},
{
"year": "2",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
},
{
"year": "3",
"idList": [
"234342",
"532542",
"325424",
"234234"
]
}
]
}
]
}
이제 이것을 아래와 같은 구조로 매핑하고 싶었습니다. .NET ProData
Framework의 각 문자열을 사용하여 초기화 할 수 있습니다 idList
.
Map<String,Map<String,List<ProData>>> finalMap
나는 아래와 같이 작성했고 작동합니다.
Map<String,Map<String,List<ProData>>> finalMap = new HashMap<>();
for(Employee employee:root.getEmployees()){
Map<String,List<ProData>> proDataMap = new HashMap<>();
for(ProData proData: employee.getProData()){
List<ProData> finalObjs = new ArrayList<>();
for(String id:proData.getIdList()){
finalObjs.add(new ProData(id));
}
proDataMap.put(proData.getYear(),finalObjs);
}
finalMap.put(employee.getName(),proDataMap);
}
스트림 API를 사용하여 더 나은 버전을 만들고 싶었습니다.
최종 결과는지도이므로 toMap
수집기를 사용하십시오 . 맵의 키는 직원 이름 (중복이 없다고 가정)이며 맵 값에는 약간 더 많은 작업이 필요합니다.
root.getEmployees().stream().collect(
Collectors.toMap(
Employee::getName,
Employee::getProDataMap
)
}
이제 작성 해보자 getProDataMap
에 Employee
. 다시 우리는 toMap
수집기를 사용합니다 . 키는 연도 (중복이 없다고 가정)이고 값은 ProData
생성자 를 사용하여 매핑 된 ID 목록 입니다.
public Map<String, List<ProData>> getProDataMap() {
return this.getProData().stream().collect(
Collectors.toMap(
ProData::getYear,
proData -> proData.getIdList().stream()
.map(ProData::new)
.collect(Collectors.toList())
)
)
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다