排序并将数字存储在哈希映射中

huangapple go评论67阅读模式
英文:

Sorting and storing number in hashmap

问题

我需要在以下情况下寻求您的帮助。

我会在列表中拥有从1到100,000的任意数字。我需要将这些数字分成10组。1-10000的数字应该位于哈希映射的第一组中,以此类推处理其他组。

我的最终映射应如下所示:

键 1 = 1-10000 值 8990
键 2 = 10001-20000 值 12000
...
键 10 = 90000-100000 值 95001

可以通过使用if循环来检查每个10000,并将其存储在相应的键中来实现。但是否有其他方法来做到这一点?是否有已经执行此操作的实用函数?

英文:

I need your help in the below scenario.

I would be having any number from 1 to 100000 in a list. I need to split those numbers it into 10 groups. Numbers from 1 - 10000 should lie into group 1 in hashmap .. similarly for remaining groups.

My final Map should be like this

Key 1= 1-10000 Value 8990
Key 2 = 10001-20000 value 12000
....
Key 10 = 90000-100000 value 95001

It can be done via if loop to check for every 10000 and store it in corresponding key. But do we have any other way to do it? Any util function which already does it?

答案1

得分: 1

你可以使用流(Stream)API中的函数 collect()int 值的列表/流转换为所需的 Map<>。在这种情况下,您可以使用 Collectors.groupingBy() 收集器,并将 (i-1)/10000+1 指定为键。这样,值将根据 i 除以 10000 的余数被放入列表中。代码可能如下所示:

List<Integer> values = Arrays.asList(1, 10, 100, 1000, 10000,
	10001, 20000, 8990, 12000, 95001,
	90000, 90001, 100000);

Map<Integer, List<Integer>> mapping = values
    .stream()
    .collect(Collectors.groupingBy(i -> (i-1)/10000+1));
System.out.println(mapping);

这将生成以下输出:

{1=[1, 10, 100, 1000, 10000, 8990],
 2=[10001, 20000, 12000],
 9=[90000],
 10=[95001, 90001, 100000]}
英文:

You can use the stream API function collect() to convert the list/stream of int values to a Map<> you want. In this case you use the Collectors.groupingBy() collector and specify (i-1)/10000+1 as the key. This way the values will put in lists based on the remainder of i divided by 10000. The code might look like this:

List<Integer> values = Arrays.asList(1, 10, 100, 1000, 10000,
	10001, 20000, 8990, 12000, 95001,
	90000, 90001, 100000);
	
Map<Integer, List<Integer>> mapping = values
    .stream()
    .collect(Collectors.groupingBy(i -> (i-1)/10000+1));
System.out.println(mapping);

This will generate the following output:

{1=[1, 10, 100, 1000, 10000, 8990],
 2=[10001, 20000, 12000],
 9=[90000],
 10=[95001, 90001, 100000]}

huangapple
  • 本文由 发表于 2020年10月3日 17:21:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/64182627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定