Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

grouping data in java

Tags:

java

jdbc

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

like image 860
JJunior Avatar asked Dec 13 '25 07:12

JJunior


1 Answers

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:

  • Collections and Maps tutorial
like image 134
BalusC Avatar answered Dec 14 '25 21:12

BalusC