使用java8计算数组列表中特定对象的出现次数

时间:2018-07-25 06:43:34

标签: java arraylist java-8

说,我有一个数组列表:

catalog id--->901
Catalog name --->series277
catalog id--->901
Catalog name --->series277
catalog id--->545
Catalog name --->series285
catalog id--->545
Catalog name --->series285
catalog id--->545
Catalog name --->series285
catalog id--->546
Catalog name --->series685
catalog id--->546
Catalog name --->series685
catalog id--->40962
Catalog name --->series19348
catalog id--->40962
Catalog name --->series19348
catalog id--->40962
Catalog name --->series19348
catalog id--->40962

从此列表中,我想找到以下发生的次数。

catalog id--->901    -- 2
catalog id--->545    -- 3
catalog id--->546    -- 2
catalog 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 个答案:

答案 0 :(得分:7)

您可以使用流:

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