gpt4 book ai didi

java - 如何获取HashMap中存在对应关系的计数?

转载 作者:行者123 更新时间:2023-12-01 07:01:19 24 4
gpt4 key购买 nike

我遇到这个问题,我需要一些东西来将区域代码与电话号码相匹配,最后我需要每个区域代码中的电话号码计数,我想我可以使用 map 。你有什么想法吗?

Example

Given area_code: 351 phone_number:123456
Given area_code: 351 phone_number:1234567
Given area_code: 111 phone_number:678904

Output
351:2 (2 is the count on the numbers)
111:1 (1 is the count on the numbers)

最佳答案

首先,创建一个包含两个字段的类,一个表示区号 (String),另一个表示电话号码 (String)。一旦完成,您就可以旋转所需的任意数量的对象;用必要的数据填充它,然后将其存储到列表中。

完成后,您可以使用 groupingBy收集器计算属于每个组(区号)的电话号码数量,如下所示:

Map<String, Long> resultSet = 
myList.stream()
.collect(Collectors.groupingBy(ClassName::getAreaCode, Collectors.counting()));

或者如果您只想打印,那么您可以这样做:

myList.stream()
.collect(Collectors.groupingBy(ClassName::getAreaCode, Collectors.counting()))
.forEach((k, v) -> System.out.println(String.join(":", k, v.toString())));

关于java - 如何获取HashMap中存在对应关系的计数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48235951/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com