[英]Algorithm to create multiple lists from a single list
I have an interface: 我有一个界面:
List<List<Integer>> separate(List<Integer> list);
I want to be able to separate the parameterized list into separate integer lists based on if the values within the list object are the same so if the list was {1, 1, 5, 7, 9}
it would create 4 separate lists: 我希望能够基于列表对象内的值是否相同,将参数化列表分为单独的整数列表,因此如果列表为
{1, 1, 5, 7, 9}
,它将创建4个单独的列表:
{1, 1}
{5}
{7}
{9}
Is there an easy library to use for this? 是否有一个易于使用的库? I can quite easily come up with an algorithm which does this but if the elements in the list were not
Integers
but Objects
and you wanted to base the grouping rules on some fields within it then how would I go about doing that? 我可以很容易地提出一个算法,但是如果列表中的元素不是
Integers
而是Objects
而您想将分组规则基于其中的某些字段,那我该怎么做呢?
Thanks very much for any help. 非常感谢您的帮助。
Generally you'd want to use a temporary Map<Key, List<Type>>
, where Key and Type would both be Integer
in your example. 通常,您需要使用一个临时
Map<Key, List<Type>>
,其中在示例中, Key和Type均为Integer
。 For each Integer
in the big list, check the Map
to see if that Integer
is already a key. 对于大列表中的每个
Integer
,请检查Map
以查看该Integer
是否已经是密钥。 If not, then add it with a new List<Integer>
. 如果不是,则添加新的
List<Integer>
。 Then either way, add the Integer
to the List
for that key. 然后,无论哪种方式,将
Integer
添加到该键的List
中。 Then at the very end, construct List<Integer>
from the values()
of the Map
. 然后,最后从
Map
的values()
构造List<Integer>
。
For a more complicated Type , you'd choose some distinguishing data value to be the Key , but otherwise the code would be analogous. 对于更复杂的Type ,您可以选择一些不同的数据值作为Key ,否则代码将是类似的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.