julien dumortier julien dumortier - 2 months ago 13
Java Question

sort list in list with comparator

i would like make a specific sort of my stream with comparator in Java 8.

I have 2 class like this:

public class A {
private String mName;
private List<B> mBObjects;

public A(String name) {
mBObjects = new ArrayList<>();
mName = name;
}

public void addValue(B b) {
mBObjects.add(b);
}

public List<B> getBObjects() {
return mBObjects;
}

public String getName() {
return mName;
}
}

public class B {
private int mValue;

public B(int value) {
mValue = value;
}

public int getValue() {
return mValue;
}
}


I initialises theses list with this code:

List<A> listOfA = new ArrayList<>();

//A 1
A a = new A("a1");
a.addValue(new B(20));
a.addValue(new B(12));
listOfA.add(a);

//A 2
a = new A("a2");
a.addValue(new B(3));
listOfA.add(a);


//A 3
a = new A("a1");
a.addValue(new B(2));
a.addValue(new B(26));
a.addValue(new B(6));
listOfA.add(a);


Now i print the lists with this code:

for(A a: listOfA) {
System.out.print("A: "+a.getName());
List<B> listOfB = a.getBObjects();
for(B b:listOfB) {
System.out.print(" ; notes: "+b.getValue());
}
System.out.println(" ");
}


the result is:

A: a1 ; value: 20 ; value: 12
A: a2 ; value: 3
A: a1 ; value: 2 ; value: 26 ; value: 6


I add this code after:

listOfA = listOfA.stream().sorted(Comparator.comparing(A::getName)).collect(Collectors.toList());


The new result of this lists is:

A: a1 ; value: 20 ; value: 12
A: a1 ; value: 2 ; value: 26 ; value: 6
A: a2 ; value: 3


For each A object, i would like sort the list mBObjects without make a foreach to obtain this result:

A: a1 ; value: 12 ; value: 20
A: a1 ; value: 2 ; value: 6 ; value: 26
A: a2 ; value: 3


Thank's !

Answer

If you want a sort that mutates the original List, use List#sort to avoid all the overhead of creating a new list. Afterwards, you can call List#sort on each of the mBObjects.

listOfA.sort(Comparator.comparing(A::getName));
listOfA.stream().forEach(a -> a.getBObjects().sort(Comparator.comparingInt(B::getValue)));
Comments