Help need with transforming Java lists/collections or something
I have a list of objects returned from getJdbcTemplate().query
that look like this
object(test,test,test,1)
obj开发者_StackOverflowect(test,test,test,2)
object(test,test,test,3)
How can I transpose these into one object that looks like this
object(test,test,test,list<t>({1,2,3}))
Hopefuly you get the idea from my ropey psuedo object representation :)
I think using RowMapper
can be a little painful. Perhaps, you can do something like this (by the way, this is my pseudo):-
List<Map> rows = getJdbcTemplate().queryForList(sql);
MyObject obj = null;
for (Map row : rows) {
// configure the first 3 fields upon object creation.
if (obj == null) {
obj = new MyObject(row.get("firstField"), row.get("secondField"), row.get("thirdField"));
}
// basically add each item into the list
obj.addToList(row.get("fourthField"));
}
JdbcTemplate
deals with rows, so you need a RowMapper
to extract the values and convert them into a List of a custom type (implement a class that corresponds to this structure object(test,test,test,1)
). Then you can work on the extracted values and assemble your new object from the list values.
Reference:
- Examples of JdbcTemplate class usage
JdbcTemplate
javadocRowMapper<T>
javadoc
Couldn't you use a 2 dimensional array?
http://www.willamette.edu/~gorr/classes/cs231/lectures/chapter9/arrays2d.htm
I'm kind of a noob at java so if I'm not correct, please excuse my ignorance.
Extend your Object Model.
You need to create a new object, similar to the one you are creating with the individual value argument, which instead takes a list or a collection as the final argument. Instead of storing a single value there, your object will store a list or a collection there. If this list or collection will be immutable once the object has been created, you should consider converting the data to an int[]
before storing it.
Then, build whatever methods you need on this new object. You can even write a method to return an array of the old objects, where each object has only one value in it.
精彩评论