tags:

views:

65

answers:

3

hi is there someway we can group similar data in java?

i want to group all the data with same id and print it out.

i am querying for the data using jdbc and was searching for a library i could use for this.

any idea? thanks

+1  A: 

Use a Map<GroupID, List<Data>>.

Map<Long, List<Data>> groups = new HashMap<Long, List<Data>>();
while (resultSet.next()) {
    Long groupId = resultSet.getLong("groupId");
    String col1 = resultSet.getString("col1");
    String col2 = resultSet.getString("col2");
    // ...
    List<Data> group = groups.get(groupId);
    if (group == null) {
        group = new ArrayList<Data>();
        groups.put(groupId, group);
    }
    group.add(new Data(groupId, col1, col2 /* ... */));
}

You could also just make it a property of another (parent) bean.

See also:

BalusC
this is like too time consuming as I have a lot of data and arraylist is not a good option :(
jillika iyer
@jillika then surely you can use a different `List` implementation?
matt b
@jillika: isn't hauling the data from DB itself more time consuming? If you are already complaining like that, it look like you're trying to haul at least a million of records in or so. Did you consider letting DB do the work of returning the data in the right format so that you don't need to remassage it in Java afterwards? Or if aplpicable, have you considered pagination?
BalusC
A: 

Ideally you should use a where clause in your SQL query to limit the returned data to the id in question:

select *
from table
where id = 'xxxxxx'

Of course if you will be printing out the data for all id's this may be a bad choice, as then your app will perform multiple sql queries, which usually will result in a performance hit.

As for grouping data in Java, take a look at java.util.HashMap (or any of the container classes that implement the Map interface). HashMap is a container of key-value pairs. In your case, the 'key' can be a String (or whichever data type applies) representing your id, and the 'value' can be an object to contain the data associated to the id key (i.e.: ArrayList of Strings, or a new class you define to help you manage the data)

new Thrall
A: 

Are you looking for the SQL ORDER BY clause?

SELECT columns
WHERE  criteria
ORDER BY id ASC;

That will give you all the data in your criteria and will order it by the id column which naturally means that all the rows with the same id will appear consecutively.

JeremyP