在地图中获取3个最大值
我正在存储lastbyfirst
变量的信息。
{Peter=[Leigh], George=[Barron, Trickett,Evans],
Paul-Courtenay=[Hyu], Ryan=[Smith], Toby=[Geller, Williams],
Simon=[Bush, Milosic, Quarterman,Brown]}
我如何打印第一个3
,该出现最多,也是popereance的数量。
我想列出3个值最多的那些。在lastByFirst
中包含类似的内容。我想以这种方式打印:
Simon: 4
George: 3
Toby:2
Map<String, List<String>> lastByFirst = PeopleProcessor.lastnamesByFirstname(PeopleSetup.people);
我的尝试就是这样:
var store = lastByFirst.entrySet()
.stream()
.collect( Collectors.groupingBy(Person::getLastName,
Collectors.counting())
.toString();
Store
应该与
Simon: 4
George: 3
Toby:2
I'm storing information of the lastByFirst
variable.
{Peter=[Leigh], George=[Barron, Trickett,Evans],
Paul-Courtenay=[Hyu], Ryan=[Smith], Toby=[Geller, Williams],
Simon=[Bush, Milosic, Quarterman,Brown]}
How can I print the first 3
which appeared the most and also the number of appereance.
I would like to list those which 3 value appeared the most. In the lastByFirst
contains something like that. I would like to print in this way:
Simon: 4
George: 3
Toby:2
Map<String, List<String>> lastByFirst = PeopleProcessor.lastnamesByFirstname(PeopleSetup.people);
My attempt was something like that:
var store = lastByFirst.entrySet()
.stream()
.collect( Collectors.groupingBy(Person::getLastName,
Collectors.counting())
.toString();
store
should be equal with
Simon: 4
George: 3
Toby:2
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是首先将列表地图转换为列表尺寸的地图,然后选择前三个尺寸的地图:
Here's one that first converts the map of lists to a map of the sizes of the list, and then picks the top three such sizes:
您可以:
You can:
如果您已经有一个由 组成的人的地图,则可以解决在线性中查找
3
最常见的最常见的问题时间 o(n)。比对整个数据集进行排序更快。如果不是选择
3
最常见的名字最常见的是m
,那么时间复杂性将为 o( n + m * log m)(对于m
的小值,将接近线性时间)。要使用流实施它,我们可以使用自定义比较器,可以使用静态方法
作为收集器的一个可变容器,我们可以使用
treemap
在自然顺序中排序,其中 key 将代表具有相同名字的人,而 value 将是一个名字本身。为了仅保留
m
最常见的名称,我们需要跟踪treemap
的大小,并且当它超过时,我们必须删除第一个条目(即具有最低键的条目)。main()
输出:
a链接在线演示
If you already have a map of people grouped by first name, you can address the problem of finding the
3
most frequent first names in a linear time O(n). Which is faster than sorting the whole data set.If instead of picking
3
most frequent first names it would be generalized tom
most frequent, then the time complexity would be O(n + m * log m) (which for small values ofm
would be close to linear time).To implement it using streams, we can utilize a custom comparator, which can be created using the static method
Collector.of()
.As a mutable container of the collector, we can use a
TreeMap
sorted in the natural order, where the key would represent the of people having the same first name and the value would be a first name itself.In order to retain only
m
most frequent names we need to track the size of theTreeMap
and when it gets exceeded we have to remove the first entry (i.e. an entry having the lowest key).main()
Output:
A link Online Demo
这是 streamex :
Here is another solution by StreamEx: