I need to sort an Iterable. It contains a Tuple4<Long,Long,String,String> and need to have it sorted on the first field of the tuple in order to calculate the time differences between the values.
Long pHandlingTime=0L;
for (Tuple4<Long, Long, String, String> in: input){
elapsed = Long.parseLong(in.getField(1).toString()) - pHandlingTime;
pHandlingTime = Long.parseLong(in.getField(1).toString())
}
Any suggestions?
Regards Hans
CodePudding user response:
Supposing you have a Collection of Tuple4, you can define your Tuple4Comparator implementing the Comparator interface (https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html). The trick is providing a compare method which will decide which of the two arguments come first.
public static class YourComparator implements Comparator<Tuple4<Long, Long, String, String>> {
// Let's compare 2 Tuple4 objects
public int compare(Tuple4<Long, Long, String, String> o1, Tuple4<Long, Long, String, String> o2)
{
// Perform comparison, returning a negative integer if o1 is lower than o2, 0 if they're equal or a positive number if it's greater
}
}
Once you have a proper comparator you can sort your Collection via:
Collections.sort(yourCollection, new YourComparator());
CodePudding user response:
Depending of what your Tuple4
is you can do something like this to sort on first field.
Assuming that a getFirst
method exists on Tuple4
:
final List<Tuple4<Long, Long, String, String>> collect = l.stream().sorted(Comparator.comparing(Tuple4::getFirst)).toList();
Assuming that a getByPos
method exists on Tuple4
:
final List<Tuple4<Long, Long, String, String>> collect2 = l.stream().sorted(Comparator.comparing(t -> t.getByPos(0))).toList();