开发者

grouping data in java

is there someway 开发者_如何学JAVAwe 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


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


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)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜