基于对象属性将java集合拆分为子集合 [英] split a java collection into sub collections based on a object property

查看:887
本文介绍了基于对象属性将java集合拆分为子集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个MyObjects列表... MyObject {int id,String name}。现在我想把列表分成具有相同id值的子列表,任何一个建议一个有效的方法这样做。

I have a List of MyObjects ... MyObject{ int id,String name}. Now I want to split the the list into sublists that have identical "id" values, can any one suggest an efficient approach for doing this.

推荐答案

// create the thing to store the sub lists
Map<Integer, List<MyObject>> subs = new HashMap<Integer, List<MyObject>>();

// iterate through your objects
for(MyObject o : list){

    // fetch the list for this object's id
    List<MyObject> temp = subs.get(o.getId());

    if(temp == null){
        // if the list is null we haven't seen an
        // object with this id before, so create 
        // a new list
        temp = new ArrayList<MyObject>();

        // and add it to the map
        subs.put(o.getId(), temp);
    }

    // whether we got the list from the map
    // or made a new one we need to add our
    // object.
    temp.add(o);
}

这篇关于基于对象属性将java集合拆分为子集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆