• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Spliting lists into sublists

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

I have an ArrayList of objects which I would like to split into sublists for some processing. My object schema is simple. The ArrayList contains 1-n objects. Each object had the following fields
* id
* value
I would like to split the arrayList into a group of sublists based on the value attribute which can be the same across multiple objects. The result should be something like the following
List value1 = new ArrayList; - which contains
Id1, value1
Id2, value1
Id3, value1
And
List value2 = new ArrayList; - which contains
Id4, value2
Id5, value2
Id6, value2
Can this be easily achieved in Java? I’ve looked at List.subLists but that does not give me the required functionality because I do not know the indexes beforehand.

Thanks in advance.
 
Sheriff
Posts: 27463
88
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That's a rather specialized requirement. No, there isn't anything in the standard API which does that. I can't even imagine you finding something like that in a collection of list-processing utilities.
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
What I'd be tempted to do is convert this into a Map of value to list of objects. Create the empty map, and then the algorithm goes something like:
- Iterate through the list of objects
- - Look at the value
- - If the map doesn't contain an entry for that value, create an empty list and add it to the map.
- - Add the object to the relevant list

That shouldn't be too complex. And you don't need to know anything about the values in advance. Any use to you?
 
Trust God, but always tether your camel... to this tiny ad.
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic