假设,我有一个数组列表:catalog id--->901Catalog name --->series277catalog id--->901Catalog name --->series277catalog id--->545Catalog name --->series285catalog id--->545Catalog name --->series285catalog id--->545Catalog name --->series285catalog id--->546Catalog name --->series685catalog id--->546Catalog name --->series685catalog id--->40962Catalog name --->series19348catalog id--->40962Catalog name --->series19348catalog id--->40962Catalog name --->series19348catalog id--->40962从这个列表中,我想找到如下所示的出现次数。catalog id--->901 -- 2catalog id--->545 -- 3catalog id--->546 -- 2catalog id--->40962 -- 4我的目标是,根据id我想创建一个循环以进一步迭代的出现次数。请找到我创建 Arraylist 的 java 代码List<Catalog> catalogList2 = new ArrayList<Catalog>();for (SearchHit hit1 : searchHits2){ sourceAsMap2 = hit1.getSourceAsMap(); catalog2 = new Catalog(); catalog2.setId(String.valueOf(sourceAsMap2.get("catalog_id"))); catalog2.setCatalog_name(String.valueOf(sourceAsMap2.get("catalog_name"))); catalogList2.add(catalog2);}更新尝试实现以下案例:for(int i=0;i<catalogList2.size();i++) { // want to find the number of occurances for catalog.getId() //Then i want to create a loop based on the number of occurances of catalog id for(int i=0;i<catalog_id_occurances.size;i++) { //Have to do something. } }
1 回答
翻过高山走不出你
TA贡献1875条经验 获得超3个赞
您可以使用 Streams 做到这一点:
catalogs.stream().collect(
Collectors.groupingBy(Catalog::getId, Collectors.counting()));
输出:
jshell> catalogList.stream().collect(
...> Collectors.groupingBy(Catalog::getId, Collectors.counting()));
$43 ==> {901=2, 545=3, 546=2, 40962=4}
- 编辑 -
如果您想进一步操作输出或想以某种客户格式打印,您可以在下面使用:
catalogList.stream().collect(Collectors.groupingBy(Catalog::getId, Collectors.counting())).entrySet().stream().map(p->"catalog id--->"+p.getKey()+" -- "+p.getValue()).forEach(System.out::println);
输出:
catalog id--->901 -- 2
catalog id--->545 -- 3
catalog id--->546 -- 2
catalog id--->40962 -- 4
添加回答
举报
0/150
提交
取消