Группировка списка основных объектов по идентификатору вложенного объекта - PullRequest
0 голосов
/ 13 июля 2020

Учитывая следующий класс A:

public class A {
    private int id; //this field is unique
    private int a_1; //this field ain't unique
    private String a_2;
    private String a_3;
    
    //setters + getters
}

Мы можем сгруппировать list случайных объектов типа A в соответствии с их соответствующими a_1:

Map<String, List<A>> sortedmap = list.stream()
                .collect(Collectors.groupingBy(A::getA_1, Collectors.toList()));

Теперь даны два класса B и C, например:

public class B{
    private int id; //this field is unique for all entities of type B
    private String b_1;
    private C b_C; //many objects of type B may have a reference to the same object of type C
    
    //setters + getters
}

public class C{
    private int id; //this field is unique for all entities of type C
    private String c_1;
    private D c_D; //many objects of type C may have a reference to the same object of type D
    
    //setters + getters
}

public class D{
    private int id; //this field is unique for all entities of type D
    private String d_1;
    private String d_2;
    
    //setters + getters
}

Как мы можем отсортировать список случайных объектов типа B по их соответствующему полю b_C.getC_D().getId()?

Ответы [ 2 ]

0 голосов
/ 13 июля 2020
• 1000 * методы. Так же, как и для собственных атрибутов B.
0 голосов
/ 13 июля 2020

Вы можете сгруппировать результаты в TreeMap, который упорядочен по умолчанию:

public static void main(String[] args) {
    D d1 = new D();d1.setId(1);
    D d2 = new D();d2.setId(2);
    
    C c1 = new C();c1.setC_D(d1);
    C c2 = new C(); c2.setC_D(d2);
    
    B b1 = new B(); b1.setB_C(c1); b1.setId(1);
    B b2 = new B(); b2.setB_C(c2); b2.setId(2);
    B b3 = new B(); b3.setB_C(c2); b3.setId(3);
    
    Map<String, List<B>> result = Arrays.asList(b1,b2,b3)
            .stream()
            .collect(Collectors.groupingBy(b -> ""+b.getB_C().getC_D().getId(),
                     TreeMap::new, 
                     Collectors.toList()));
        
    System.out.println(result);
}

Результат:

{1=[B [id=1]], 2=[B [id=2], B [id=3]]}

PS. @javaistaucheineinsel приятное имя пользователя;)

...