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}
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?
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. For each Integer
in the big list, check the Map
to see if that Integer
is already a key. If not, then add it with a new List<Integer>
. Then either way, add the Integer
to the List
for that key. Then at the very end, construct List<Integer>
from the values()
of the Map
.
For a more complicated Type , you'd choose some distinguishing data value to be the Key , but otherwise the code would be analogous.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.