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

假设,我有一个数组列表:


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.

        }


    }


RISEBY
浏览 452回答 1
1回答

翻过高山走不出你

您可以使用 Streams 做到这一点:catalogs.stream().collect(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Collectors.groupingBy(Catalog::getId, Collectors.counting()));输出:jshell> catalogList.stream().collect(&nbsp; &nbsp;...>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;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()+"&nbsp; &nbsp; -- "+p.getValue()).forEach(System.out::println);输出:catalog id--->901&nbsp; &nbsp; -- 2catalog id--->545&nbsp; &nbsp; -- 3catalog id--->546&nbsp; &nbsp; -- 2catalog id--->40962&nbsp; -- 4
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java