根据对象属性将java集合拆分为子集合

发布于 2024-09-25 15:34:38 字数 100 浏览 2 评论 0原文

我有一个 MyObjects 列表... MyObject{ int id,String name}。现在我想将列表拆分为具有相同“id”值的子列表。谁能建议一种有效的方法来做到这一点?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

归途 2024-10-02 15:34:38

如果您使用 JDK 1.8,您可以使用一个优雅的解决方案,例如:

Map<Integer, List<MyObject>> myObjectsPerId =
    myObjects.stream().collect(Collectors.groupingBy(MyObject::getId));

If you are using JDK 1.8, you can use an elegant solution like:

Map<Integer, List<MyObject>> myObjectsPerId =
    myObjects.stream().collect(Collectors.groupingBy(MyObject::getId));
嘿嘿嘿 2024-10-02 15:34:38
// 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);
}
// 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);
}
只涨不跌 2024-10-02 15:34:38

使用番石榴

ListMultimap<Integer, MyObject> myObjectsById = Multimaps.index(myObjects,
    new Function<MyObject, Integer>() {
      public Integer apply(MyObject myObject) {
        return myObject.id;
      }
    });

Using Guava:

ListMultimap<Integer, MyObject> myObjectsById = Multimaps.index(myObjects,
    new Function<MyObject, Integer>() {
      public Integer apply(MyObject myObject) {
        return myObject.id;
      }
    });
浮云落日 2024-10-02 15:34:38

循环遍历元素,检查其 id 值,并将它们放入以 id 作为键的 Hashtable 中。这就是 O(N),它是您所能达到的最高效率。

Loop through the elements, check their id values, and place them in a Hashtable with id as the key. That's O(N), which is as efficient as you're going to get.

岁月蹉跎了容颜 2024-10-02 15:34:38

使用 JDK 1.8:

List<MyObject> objects= new ArrayList();
Map<Integer, List<MyObject>> obejctMap = new HashMap();
objects.stream().map(MyObject::getId).distinct().forEach(id -> obejctMap .put(id,
              objects.stream().filter(object -> id.equals(object.getId())).collect(Collectors.toList())));

Using JDK 1.8:

List<MyObject> objects= new ArrayList();
Map<Integer, List<MyObject>> obejctMap = new HashMap();
objects.stream().map(MyObject::getId).distinct().forEach(id -> obejctMap .put(id,
              objects.stream().filter(object -> id.equals(object.getId())).collect(Collectors.toList())));
莫多说 2024-10-02 15:34:38
ArrayList<MyObject> list=new ArrayList<MyObject>();
//fill Objects..
HashMap<Integer,ArrayList<MyObject>> hash=new HashMap<Integer,ArrayList<MyObject>>();
for(MyObject elem:list)//iterate the list
{
ArrayList<MyObject> tmp=null; //temporary variable 
if((tmp=hash.get(elem.getId()))==null) // check if id already present in map
 {
  tmp=new ArrayList<MyObject>();   
  hash.put(elem.getId(),tmp); //if not put a new array list
 }
names.add(elem); //if present add the name to arraylist
}
ArrayList<MyObject> list=new ArrayList<MyObject>();
//fill Objects..
HashMap<Integer,ArrayList<MyObject>> hash=new HashMap<Integer,ArrayList<MyObject>>();
for(MyObject elem:list)//iterate the list
{
ArrayList<MyObject> tmp=null; //temporary variable 
if((tmp=hash.get(elem.getId()))==null) // check if id already present in map
 {
  tmp=new ArrayList<MyObject>();   
  hash.put(elem.getId(),tmp); //if not put a new array list
 }
names.add(elem); //if present add the name to arraylist
}
行雁书 2024-10-02 15:34:38

使用 Map.computeIfAbsent 方法,从 Java 8 开始也可用:

Map<Integer, List<MyObject>> res = new HashMap<>();
for (MyObject obj : myObjects) {
  res.computeIfAbsent(obj.getId(), k -> new ArrayList<>()).add(obj);
}

Alternative to Collectors.groupingBy solution using Map.computeIfAbsent method, which is also available starting from Java 8:

Map<Integer, List<MyObject>> res = new HashMap<>();
for (MyObject obj : myObjects) {
  res.computeIfAbsent(obj.getId(), k -> new ArrayList<>()).add(obj);
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文