按属性对对象列表进行分组

160

我需要使用特定对象的属性(Location)对对象列表(Student)进行分组。 代码如下:

public class Grouping {
    public static void main(String[] args) {

        List<Student> studlist = new ArrayList<Student>();
        studlist.add(new Student("1726", "John", "New York"));
        studlist.add(new Student("4321", "Max", "California"));
        studlist.add(new Student("2234", "Andrew", "Los Angeles"));
        studlist.add(new Student("5223", "Michael", "New York"));
        studlist.add(new Student("7765", "Sam", "California"));
        studlist.add(new Student("3442", "Mark", "New York"));

    }
}

class Student {
    String stud_id;
    String stud_name;
    String stud_location;

    Student(String sid, String sname, String slocation) {
        this.stud_id = sid;
        this.stud_name = sname;
        this.stud_location = slocation;
    }
}

请给我提供一个清晰的方法来完成它。


3
一个哈希映射,以位置作为键,学生列表作为值。 - Omoro
按位置排序能解决你的问题吗,还是有其他的原因? - Warlord
尝试使用 Comparator 并按位置排序。 - pshemek
1
@Warlord 是的,但是如果我需要获取像按地点分组的学生数量这样的信息,最好能够进行分组。 - Dilukshan Mahendra
我认为这里的答案https://dev59.com/oWoy5IYBdhLWcg3wkO6g#8464106也适用于这个问题。 - Fabricio Buzeto
显示剩余2条评论
13个回答

372

在Java 8中:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

1
这是因为在Student类中,stud_location被指定为友好类型。只有Student类和与Student在同一包中定义的任何类才能访问stud_location。 如果您将String stud_location;替换为public String stud_location;,则应该可以正常工作。或者您可以定义一个getter函数。更多信息请参见https://www.cs.princeton.edu/courses/archive/spr96/cs333/java/tutorial/java/javaOO/accesscontrol.html - Eranga Heshan
简单而优雅的解决方案 - Himanshu Gupta

148

这将使用locationID作为键将学生对象添加到HashMap中。

HashMap<Integer, List<Student>> hashMap = new HashMap<Integer, List<Student>>();

遍历此代码并将学生添加到HashMap

if (!hashMap.containsKey(locationId)) {
    List<Student> list = new ArrayList<Student>();
    list.add(student);

    hashMap.put(locationId, list);
} else {
    hashMap.get(locationId).add(student);
}

如果您想获取带有特定位置详细信息的所有学生,则可以使用以下内容:

hashMap.get(locationId);

这将为您获取所有与相同位置ID的学生。


4
你声明了一个 Location 对象的列表,在下一行你向之前的列表添加了一个 Student 对象,这应该会引发一个错误。 - OJVM
当 hashMap.containskey() 返回 false 时,hashMap.get() 返回 null。如果您首先调用 hashMap.get(),将结果存储在本地变量中,并检查此本地变量是否为 null,则可以节省对 containsKey() 方法的调用。 - Esteve

35
Map<String, List<Student>> map = new HashMap<String, List<Student>>();

for (Student student : studlist) {
    String key  = student.stud_location;
    if(map.containsKey(key)){
        List<Student> list = map.get(key);
        list.add(student);

    }else{
        List<Student> list = new ArrayList<Student>();
        list.add(student);
        map.put(key, list);
    }

}

16

Java 8的groupingBy收集器

可能有点晚了,但我想分享一个改进的思路来解决这个问题。这基本上与@Vitalii Fedorenko的答案相同,但更容易操作。

您只需通过将分组逻辑作为函数参数传递给Collectors.groupingBy(),即可获得分割后带有键参数映射的列表。请注意,使用Optional是为了避免当提供的列表为null时出现不必要的NPE。

public static <E, K> Map<K, List<E>> groupBy(List<E> list, Function<E, K> keyFunction) {
    return Optional.ofNullable(list)
            .orElseGet(ArrayList::new)
            .stream()
            .collect(Collectors.groupingBy(keyFunction));
}

现在你可以使用它来按任何东西进行分组。针对这里的问题,

Map<String, List<Student>> map = groupBy(studlist, Student::getLocation);

也许你也想看看这个 Java 8 groupingBy Collector 指南


12
使用Java 8
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Student {

    private String stud_id;
    private String stud_name;
    private String stud_location;

    public String getStud_id() {
        return stud_id;
    }

    public String getStud_name() {
        return stud_name;
    }

    public String getStud_location() {
        return stud_location;
    }



    Student(String sid, String sname, String slocation) {

        this.stud_id = sid;
        this.stud_name = sname;
        this.stud_location = slocation;

    }
}

class Temp
{
    public static void main(String args[])
    {

        Stream<Student> studs = 
        Stream.of(new Student("1726", "John", "New York"),
                new Student("4321", "Max", "California"),
                new Student("2234", "Max", "Los Angeles"),
                new Student("7765", "Sam", "California"));
        Map<String, Map<Object, List<Student>>> map= studs.collect(Collectors.groupingBy(Student::getStud_name,Collectors.groupingBy(Student::getStud_location)));
                System.out.println(map);//print by name and then location
    }

}

结果将是:
{
    Max={
        Los Angeles=[Student@214c265e], 
        California=[Student@448139f0]
    }, 
    John={
        New York=[Student@7cca494b]
    }, 
    Sam={
        California=[Student@7ba4f24f]
    }
}

1
这个答案可以通过沿用问题中的相同示例来改进。此外,结果与问题中请求的期望输出不匹配。 - BitfulByte
1
很好的解释。 - user2045474
不要把Java代码写成C开发人员的样子 :D - Dumbo

5

您可以使用以下内容:

Map<String, List<Student>> groupedStudents = new HashMap<String, List<Student>>();
for (Student student: studlist) {
    String key = student.stud_location;
    if (groupedStudents.get(key) == null) {
        groupedStudents.put(key, new ArrayList<Student>());
    }
    groupedStudents.get(key).add(student);
}

//打印

Set<String> groupedStudentsKeySet = groupedCustomer.keySet();
for (String location: groupedStudentsKeySet) {
   List<Student> stdnts = groupedStudents.get(location);
   for (Student student : stdnts) {
        System.out.println("ID : "+student.stud_id+"\t"+"Name : "+student.stud_name+"\t"+"Location : "+student.stud_location);
    }
}

4

使用比较器在Java中实现SQL GROUP BY功能,比较器将比较您的列数据并对其进行排序。基本上,如果您保持排序后的数据看起来像分组数据,例如如果您具有相同重复的列数据,则排序机制将对它们进行排序,将相同的数据放在一侧,然后查找不同的数据。这间接地视为相同数据的分组。

public class GroupByFeatureInJava {

    public static void main(String[] args) {
        ProductBean p1 = new ProductBean("P1", 20, new Date());
        ProductBean p2 = new ProductBean("P1", 30, new Date());
        ProductBean p3 = new ProductBean("P2", 20, new Date());
        ProductBean p4 = new ProductBean("P1", 20, new Date());
        ProductBean p5 = new ProductBean("P3", 60, new Date());
        ProductBean p6 = new ProductBean("P1", 20, new Date());

        List<ProductBean> list = new ArrayList<ProductBean>();
        list.add(p1);
        list.add(p2);
        list.add(p3);
        list.add(p4);
        list.add(p5);
        list.add(p6);

        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean) iterator.next();
            System.out.println(bean);
        }
        System.out.println("******** AFTER GROUP BY PRODUCT_ID ******");
        Collections.sort(list, new ProductBean().new CompareByProductID());
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean) iterator.next();
            System.out.println(bean);
        }

        System.out.println("******** AFTER GROUP BY PRICE ******");
        Collections.sort(list, new ProductBean().new CompareByProductPrice());
        for (Iterator iterator = list.iterator(); iterator.hasNext();) {
            ProductBean bean = (ProductBean) iterator.next();
            System.out.println(bean);
        }
    }
}

class ProductBean {
    String productId;
    int price;
    Date date;

    @Override
    public String toString() {
        return "ProductBean [" + productId + " " + price + " " + date + "]";
    }
    ProductBean() {
    }
    ProductBean(String productId, int price, Date date) {
        this.productId = productId;
        this.price = price;
        this.date = date;
    }
    class CompareByProductID implements Comparator<ProductBean> {
        public int compare(ProductBean p1, ProductBean p2) {
            if (p1.productId.compareTo(p2.productId) > 0) {
                return 1;
            }
            if (p1.productId.compareTo(p2.productId) < 0) {
                return -1;
            }
            // at this point all a.b,c,d are equal... so return "equal"
            return 0;
        }
        @Override
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);
        }
    }

    class CompareByProductPrice implements Comparator<ProductBean> {
        @Override
        public int compare(ProductBean p1, ProductBean p2) {
            // this mean the first column is tied in thee two rows
            if (p1.price > p2.price) {
                return 1;
            }
            if (p1.price < p2.price) {
                return -1;
            }
            return 0;
        }
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);
        }
    }

    class CompareByCreateDate implements Comparator<ProductBean> {
        @Override
        public int compare(ProductBean p1, ProductBean p2) {
            if (p1.date.after(p2.date)) {
                return 1;
            }
            if (p1.date.before(p2.date)) {
                return -1;
            }
            return 0;
        }
        @Override
        public boolean equals(Object obj) {
            // TODO Auto-generated method stub
            return super.equals(obj);
        }
    }
}

以上ProductBean列表的输出已按照GROUP BY标准完成,如果您查看输入数据,即给定的ProductBean列表到Collections.sort(list,Comparator对象)中,这将基于您的比较器实现进行排序,并且您将能够在下面的输出中看到分组数据。希望这可以帮助...

    ******** GROUPING之前的输入数据如下 ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ******** GROUP BY PRODUCT_ID之后的输出如下 ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]
******** GROUP BY PRICE之后的输出如下 ****** ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014] ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]

1
请不要多次发布相同的答案,也请不要发布没有解释其工作原理以及如何解决上述问题的原始代码。 - Mat
抱歉伙计,粘贴代码时出了一些错误,可能会出现多次。我已经编辑了我发布的说明。希望现在看起来没问题了吗? - Ravi Beli
我可能漏掉了什么,或者这段代码是按照一个字段排序而不是分组吗?我看到产品按ID排序,然后按价格排序。 - funder7

1
public class Test9 {

    static class Student {

        String stud_id;
        String stud_name;
        String stud_location;

        public Student(String stud_id, String stud_name, String stud_location) {
            super();
            this.stud_id = stud_id;
            this.stud_name = stud_name;
            this.stud_location = stud_location;
        }

        public String getStud_id() {
            return stud_id;
        }

        public void setStud_id(String stud_id) {
            this.stud_id = stud_id;
        }

        public String getStud_name() {
            return stud_name;
        }

        public void setStud_name(String stud_name) {
            this.stud_name = stud_name;
        }

        public String getStud_location() {
            return stud_location;
        }

        public void setStud_location(String stud_location) {
            this.stud_location = stud_location;
        }

        @Override
        public String toString() {
            return " [stud_id=" + stud_id + ", stud_name=" + stud_name + "]";
        }

    }

    public static void main(String[] args) {

        List<Student> list = new ArrayList<Student>();
        list.add(new Student("1726", "John Easton", "Lancaster"));
        list.add(new Student("4321", "Max Carrados", "London"));
        list.add(new Student("2234", "Andrew Lewis", "Lancaster"));
        list.add(new Student("5223", "Michael Benson", "Leeds"));
        list.add(new Student("5225", "Sanath Jayasuriya", "Leeds"));
        list.add(new Student("7765", "Samuael Vatican", "California"));
        list.add(new Student("3442", "Mark Farley", "Ladykirk"));
        list.add(new Student("3443", "Alex Stuart", "Ladykirk"));
        list.add(new Student("4321", "Michael Stuart", "California"));

        Map<String, List<Student>> map1  =

                list
                .stream()

            .sorted(Comparator.comparing(Student::getStud_id)
                    .thenComparing(Student::getStud_name)
                    .thenComparing(Student::getStud_location)
                    )

                .collect(Collectors.groupingBy(

                ch -> ch.stud_location

        ));

        System.out.println(map1);

/*
  Output :

{Ladykirk=[ [stud_id=3442, stud_name=Mark Farley], 
 [stud_id=3443, stud_name=Alex Stuart]], 

 Leeds=[ [stud_id=5223, stud_name=Michael Benson],  
 [stud_id=5225, stud_name=Sanath Jayasuriya]],


  London=[ [stud_id=4321, stud_name=Max Carrados]],


   Lancaster=[ [stud_id=1726, stud_name=John Easton],  

   [stud_id=2234, stud_name=Andrew Lewis]], 


   California=[ [stud_id=4321, stud_name=Michael Stuart],  
   [stud_id=7765, stud_name=Samuael Vatican]]}
*/


    }// main
}

0
Function<Student, List<Object>> compositKey = std ->
                Arrays.asList(std.stud_location());
        studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));

如果您想要添加多个对象进行分组,只需在compositKey方法中用逗号分隔添加对象即可:

Function<Student, List<Object>> compositKey = std ->
                Arrays.asList(std.stud_location(),std.stud_name());
        studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));

0

你可以使用 guavaMultimaps

@Canonical
class Persion {
     String name
     Integer age
}
List<Persion> list = [
   new Persion("qianzi", 100),
   new Persion("qianzi", 99),
   new Persion("zhijia", 99)
]
println Multimaps.index(list, { Persion p -> return p.name })

它会输出:

[qianzi:[com.ctcf.message.Persion(qianzi, 100),com.ctcf.message.Persion(qianzi, 88)],zhijia:[com.ctcf.message.Persion(zhijia, 99)]]


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接