I have the below working code using one value to compare but want to compare with two values. I need to add one more filter as "getAddressID" along with getAction. Could some help me to modify the below code?
List<Data> finalData = dataList.stream().collect(
Collectors.collectingAndThen(
Collectors.toCollection(
() -> new TreeSet<>(Comparator.comparing(Data::getAction))),
ArrayList::new))
public class TestCollection {
/**
* @param args
*/
public static void main(String[] args) {
List<Data> dataList = new ArrayList<Data>();
Data data1 = new Data("DELIVERED", "1112");
Data data2 = new Data("DELIVERED", "1113");
Data data3 = new Data("PICKEUP", "1112");
Data data4 = new Data("PICKEUP", "1112");
dataList.add(data1);
dataList.add(data2);
dataList.add(data3);
dataList.add(data4);
//Filer by Action
List<Data> finalData = dataList.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<> (Comparator.comparing(Data::getAction))), ArrayList::new));
for(Data data : finalData) {
System.out.println(" Action " + data.getAction() + " Address ID " + data.getAddressID());
}
}
}
The result is : "Action DELIVERED Address ID 1112" "Action PICKEUP Address ID 1112"
But I want result as: "DELIVERED Address ID 1112" "DELIVERED Address ID 1113" "PICKEUP Address ID 1112"
You can chain your comparators using thenComparing
, ie
new TreeSet<>(Comparator.comparing(Data::getAction).thenComparing(Comparator.comparing(Data::otherMethod))