如果kecamatan具有相同的数组值,则跟随Json的人需要按kecamatan分组以获取desa数组以及计数。
{
"data": [
{
"ID": 47,
"kecamatan": "Benteng",
"desa": "Benteng Selatan"
},
{
"ID": 48,
"kecamatan": "Benteng",
"desa": "Benteng Selatan"
},
{
"ID": 49,
"kecamatan": "Benteng",
"desa": "Benteng Utara"
},
{
"ID": 50,
"kecamatan": "Bontomantene",
"desa": "Garaupa"
}
]
}
预期产量:-
奔腾[Benteng selatan] = 2
奔腾[Benteng Utara] = 1
Bontomantene [Garaupa] = 1
最佳答案
您的问题可以被视为“计算按字段kecamatan和desa分组的列表中某个元素的出现次数”。
因此,如果可以将给定的JSON字符串转换为对象列表(例如List<Data>
),则可以使用Stream
和Lambda Expression
(自Java 8开始)计算出现次数,如下所示:
POJO
class MyDatas {
private List<MyData> data;
//general getters and setters
}
@JsonIgnoreProperties(ignoreUnknown = true)
class MyData {
private String kecamatan;
private String desa;
public String getGroupBy() {
return String.format("%s [%s]", this.getKecamatan(), this.getDesa());
}
//general getters and setters
}
对于类
MyData
,我创建一个方法getGroupBy()
,该方法返回用于分组的键。程式码片段
ObjectMapper mapper = new ObjectMapper();
MyDatas myDatas = mapper.readValue(jsonStr, MyDatas.class);
Map<String, Long> counting = myDatas.getData()
.stream()
.collect(Collectors.groupingBy(
MyData::getGroupBy, Collectors.counting()));
System.out.println(counting);
首先使用
Jackson
将JSON字符串转换为POJO,然后使用Collectors.groupingBy()
计算MyData::getGroupBy
的出现次数。控制台输出
{Bontomantene [Garaupa] = 1,Benteng [Benteng Selatan] = 2,Benteng [Benteng Utara] = 1}