Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 按属性对对象列表进行分组_Java_List_Grouping - Fatal编程技术网

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

Java 按属性对对象列表进行分组,java,list,grouping,Java,List,Grouping,我需要使用特定对象的属性(Location)对对象列表(Student)进行分组。代码如下所示: public class Grouping { public static void main(String[] args) { List<Student> studlist = new ArrayList<Student>(); studlist.add(new Student("1726", "Joh

我需要使用特定对象的属性(
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;
    }
}
公共类分组{
公共静态void main(字符串[]args){
List studlist=new ArrayList();
新增(新学生(“1726”、“约翰”、“纽约”);
新增(新学生(“4321”、“Max”、“California”);
新增(新学生(“2234”、“安德鲁”、“洛杉矶”);
新增(新学生(“5223”、“迈克尔”、“纽约”);
新增(新生(“7765”、“山姆”、“加利福尼亚”);
新增(新学生(“3442”,“马克”,“纽约”));
}
}
班级学生{
串螺柱;
字符串名称;
管柱位置;
学生(字符串sid、字符串sname、字符串位置){
this.stud_id=sid;
this.stud_name=sname;
此.stud_位置=插槽位置;
}
}
请给我一个干净的方法。你可以这样做:

Map<String, List<Student>> map = new HashMap<String, List<Student>>();
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1726", "John", "New York"));
map.put("New York", studlist);

这将把students对象添加到带有
locationID
键的中

HashMap<Integer, List<Student>> hashMap = new HashMap<Integer, List<Student>>();
如果您想让所有学生了解特定的位置详细信息,那么您可以使用:

hashMap.get(locationId);

这将使您获得具有相同位置ID的所有学生。

您可以按如下方式排序:

    Collections.sort(studlist, new Comparator<Student>() {

        @Override
        public int compare(Student o1, Student o2) {
            return o1.getStud_location().compareTo(o2.getStud_location());
        }
    });
Collections.sort(studlist,newcomparator(){
@凌驾
公共整数比较(学生o1,学生o2){
返回o1.getStud_location().compareTo(o2.getStud_location());
}
});

假设您在学生课堂上也有位置获取工具。

您可以使用以下工具:

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);
}
Map groupedStudents=newhashmap();
用于(学生:学生名单){
字符串键=student.stud\u位置;
if(groupedStudents.get(key)==null){
groupedStudents.put(key,newarraylist());
}
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);
    }
}
Set-groupedStudentsKeySet=groupedCustomer.keySet();
for(字符串位置:groupedStudentsKeySet){
List stdnts=groupedStudents.get(位置);
适用于(学生:stdnts){
System.out.println(“ID:+student.stud\u ID+”\t“+”名称:“+student.stud\u名称+”\t“+”位置:“+student.stud\u位置”);
}
}
Map Map=newhashmap();
用于(学生:学生名单){
字符串键=student.stud\u位置;
if(地图容器(图例)){
List=map.get(键);
列表。添加(学生);
}否则{
列表=新的ArrayList();
列表。添加(学生);
地图。放置(键、列表);
}
}

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

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);
        }
    }
}
公共类GroupByFeatureInJava{
公共静态void main(字符串[]args){
ProductBean p1=新ProductBean(“p1”,20,新日期());
ProductBean p2=新ProductBean(“P1”,30,新日期());
ProductBean p3=新ProductBean(“P2”,20,新日期());
ProductBean p4=新ProductBean(“P1”,20,新日期());
ProductBean p5=新ProductBean(“P3”,60,新日期());
ProductBean p6=新ProductBean(“P1”,20,新日期());
列表=新的ArrayList();
列表。添加(p1);
列表。添加(p2);
列表。添加(p3);
列表。添加(p4);
增加(p5);
增加(第6页);
for(Iterator Iterator=list.Iterator();Iterator.hasNext();){
ProductBean=(ProductBean)迭代器;
System.out.println(bean);
}
System.out.println(“*********在按产品划分的组后面**********”;
Collections.sort(list,new ProductBean().new CompareByProductID());
for(Iterator Iterator=list.Iterator();Iterator.hasNext();){
ProductBean=(ProductBean)迭代器;
System.out.println(bean);
}
System.out.println(“*********后按价格分组*******”;
Collections.sort(list,new ProductBean().new CompareByProductPrice());
for(Iterator Iterator=list.Iterator();Iterator.hasNext();){
ProductBean=(ProductBean)迭代器;
System.out.println(bean);
}
}
}
类ProductBean{
字符串productId;
国际价格;
日期;
@凌驾
公共字符串toString(){
返回“ProductBean[”+productId+“”+price+“”+date+“”]”;
}
ProductBean(){
}
ProductBean(字符串productId,int price,Date){
this.productId=productId;
这个价格=价格;
this.date=日期;
}
类CompareByProductID实现Comparator{
公共int比较(ProductBean p1、ProductBean p2){
如果(p1.productId.compareTo(p2.productId)>0){
返回1;
}
如果(p1.productId.compareTo(p2.productId)<0){
返回-1;
}
//此时所有a.b,c,d都相等…所以返回“相等”
返回0;
}
@凌驾
公共布尔等于(对象obj){
//TODO自动生成的方法存根
返回super.equals(obj);
}
}
类CompareByProductPrice实现Comparator{
@凌驾
公共int比较(ProductBean p1、ProductBean p2){
//这意味着第一列并列在两行中
如果(p1.价格>p2.价格){
返回1;
}
如果(p1.价格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);
    }
}
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);
    }

}
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);
        }
    }
}
******** BEFORE GROUPING INPUT DATA LOOKS THIS WAY ****** 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] ******** AFTER 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] ******** AFTER 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]
Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

class Student {

    String stud_id;
    String stud_name;
    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]
    }
}
@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 })
Function<Student, List<Object>> compositKey = std ->
                Arrays.asList(std.stud_location());
        studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));
Function<Student, List<Object>> compositKey = std ->
                Arrays.asList(std.stud_location(),std.stud_name());
        studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));
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
}
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));
}