programing

속성별로 개체 목록 그룹화

goodjava 2022. 11. 2. 00:27

속성별로 개체 목록 그룹화

오브젝트 목록을 그룹화할 필요가 있습니다(StudentAtribute( )를 사용합니다.Location)를 참조해 주세요.코드는 다음과 같습니다.

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;
    }
}

깔끔한 방법을 제안해 주세요.

Java 8의 경우:

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

이렇게 하면 학생 객체가 에 추가됩니다.locationID키로서

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가 동일한 모든 학생들이 받게 될 겁니다

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);
    }

}

Java 8 groupingBy Collector

늦은 감이 있지만 이 문제에 대한 개선된 아이디어를 공유하고 싶습니다.기본적으로는 @Vitalii Fedorenko의 답변과 같지만, 보다 쉽게 플레이할 수 있습니다.

를 사용하면 됩니다.Collectors.groupingBy()그룹화 로직을 기능 파라미터로 전달하면 키 파라미터 매핑이 포함된 분할 목록을 얻을 수 있습니다.를 사용하는 것에 주의해 주세요.Optional지정된 목록이 다음과 같은 경우 불필요한 NPE를 피하기 위해 사용됩니다.null

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 grouping By Collector에 대한 가이드도 살펴보시기 바랍니다.

Java 8 사용

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]
    }
}

다음을 사용할 수 있습니다.

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);
    }
}

비교기를 사용하여 Java에서 SQL GROUP BY Feature를 구현하면 비교기에서 열 데이터를 비교하여 정렬합니다.기본적으로 그룹화된 데이터처럼 보이는 정렬된 데이터를 보관하는 경우(예: 동일한 반복된 열 데이터가 있는 경우) 정렬 메커니즘은 동일한 데이터를 한쪽에 보관하는 정렬한 다음 다른 데이터인 다른 데이터를 찾습니다.이는 간접적으로 동일한 데이터의 GROUPING으로 간주됩니다.

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 to Collections.sort 목록이 표시된 경우 입력 데이터가 표시됩니다(목록, 필수 열의 비교기 개체).이것은 비교기 구현에 따라 정렬되며 아래 출력에서 그룹화된 데이터를 볼 수 있습니다.이게 도움이 되길...

******* 그룹화 전 입력 데이터 표시*******ProductBean [P1 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P1 30 월 11월 17일 09:31:01 IST 2014]ProductBean [P2 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P1 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P3 60 월 11월 17일 09:31:01 IST 2014]ProductBean [P1 20 월 11월 17일 09:31:01 IST 2014]******* 제품 ID별 그룹화 후 ********ProductBean [P1 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P1 30 월 11월 17일 09:31:01 IST 2014]ProductBean [P1 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P1 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P2 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P3 60 월 11월 17일 09:31:01 IST 2014]
******* 가격별 그룹화 후 *******ProductBean [P1 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P1 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P2 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P1 20 월 11월 17일 09:31:01 IST 2014]ProductBean [P1 30 월 11월 17일 09:31:01 IST 2014]ProductBean [P3 60 월 11월 17일 09:31:01 IST 2014]
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
}

다음과 같이 할 수 있습니다.

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);

키는 위치와 학생의 가치 리스트가 될 것입니다.따라서 나중에 다음 항목만 사용하여 학생 그룹을 얻을 수 있습니다.

studlist = map.get("New York");

하면 .guava의 »Multimaps

@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 ] 。페르시온(지아, 99)]

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

로 여러 할 수 .compositKey「CHANGE MARGE:」

Function<Student, List<Object>> compositKey = std ->
                Arrays.asList(std.stud_location(),std.stud_name());
        studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));
  @Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (o == null || getClass() != o.getClass()) return false;
    KeyValuePair<?, ?> that = (KeyValuePair<?, ?>) o;
    return Objects.equals(key, that.key) && Objects.equals(value, that.value);
}

@Override
public int hashCode() {
    return Objects.hash(key, value);
}

다음과 같이 정렬할 수 있습니다.

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

        @Override
        public int compare(Student o1, Student o2) {
            return o1.getStud_location().compareTo(o2.getStud_location());
        }
    });

Student 클래스의 장소에 대한 getter도 있다고 가정해 보겠습니다.

언급URL : https://stackoverflow.com/questions/21678430/group-a-list-of-objects-by-an-attribute