Home > Blockchain >  Sort a nested List on two elements
Sort a nested List on two elements

Time:07-09

I have a nested list, named outputToStore whose contents are given below:

[[Final, 331, M, 22/03/2020 00:00:00], 
 [Initial, 335, M, 22/06/2022 00:00:00], 
 [Exception, 335, M, 22/05/2022 00:00:00], 
 [Final, 335, M, 20/06/2022 00:00:00], 
 [Keep, 335, M, 02/06/2022 11:00:00], 
 [Final, 335, M, 10/04/2022 02:00:00], 
 [Deleted, 335, M, 22/06/2022 15:55:10],
 [Exception, 335, M, 22/06/2022 15:55:09], 
 [Final, 335, M, 22/06/2022 15:56:00], 
 [Initial, 335, M, 11/06/2022 00:00:00]]

I need to sort this based on 2 conditions: The first is a custom order: "Initial","Final","Deleted","Keep","Exception" and then based on datetime.

I am able to do it, but not sure that this is the best way to do it.

My code:

List<String> definedOrder = Arrays.asList("Initial","Final","Deleted","Keep","Exception");
Collections.sort(outputToStore, Comparator.comparing(o -> Integer.valueOf(definedOrder.indexOf(o.get(0)))));
Collections.sort(outputToStore,( o1, o2)-> {
    // let your comparator look up your car's color in the custom order
    try {
        if(Integer.valueOf(definedOrder.indexOf(o1.get(0))).compareTo(Integer.valueOf(definedOrder.indexOf(o2.get(0))))==0){
            Date date1=simpleDateFormat.parse(o1.get(3));
            Date date2=simpleDateFormat.parse(o2.get(3));
            return date1.compareTo(date2);
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    return 0;
});

I'm getting the desired result:

[[Initial, 335, M, 11/06/2022 00:00:00],
 [Initial, 335, M, 22/06/2022 00:00:00],
 [Final, 331, M, 22/03/2020 00:00:00],
 [Final, 335, M, 10/04/2022 02:00:00],
 [Final, 335, M, 20/06/2022 00:00:00],
 [Final, 335, M, 22/06/2022 15:56:00],
 [Deleted, 335, M, 22/06/2022 15:55:10],
 [Keep, 335, M, 02/06/2022 11:00:00],
 [Exception, 335, M, 22/05/2022 00:00:00],
 [Exception, 335, M, 22/06/2022 15:55:09]]

But is there any better or concise way to do it?

CodePudding user response:

Use the Power of Objects

The way you're representing your data is inconvenient and error-prone.

It clearly has to be an object having attributes of appropriate types, and not a list of strings. It's misuse of collections

Using String as a type for numbers, dates, etc. doesn't give you any advantage. There's nothing you can do with string without parsing apart from printing on the console. Proper data-types give you access to their unique behavior that String can't offer you.

The first property, let's call it status might be an enum. Enum - is a special kind of class, they are very handy when you need to represent a limit set of values, and they have a natural order, that is the same as the order of the enum-constants.

And to represent date-time information we can use one of the Java 8 classes from java.time package. In the example below, I'll use LocalDateTime.

That how such a class might look like:

public class Foo {
    public enum Status {INITIAL, FINAL, DELETED, KEEP, EXCEPTION}
    
    private CountComponents.Foo.Status status;
    private int value1;
    private String value2;
    private LocalDateTime dateTime;
    
    // constructor, getters, etc.
}

Building Comparators with Java 8

In order to sort a list of Foo objects, we need to define a comparator.

For that, we can use static methods that were introduced in the Comparator interface with Java 8. We can chain these methods in a fluent way because each of them gives a comparator.

Comparator<Foo> byStatusByDate =
    Comparator.comparing(Foo::getStatus)
        .thenComparing(Foo::getDateTime);

Note: we need to define the sorting logic in a single comparator. Don't sort the data twice like you've done in your code, it causes unnecessary performance overhead.

To learn how to build comparators using Java-8 methods, have a look at this tutorial.

And to sort a list of Foo objects, we can use method List.sort() which was introduced in Java 9 as a more fluent alternative to Collections.sort():

List<Foo> foos = // initializing the list
    
foos.sort(byStatusByDate);

Parsing the data

If data comes to you as a collection of string, then you need to parse it.

For that we need to enhance Foo and its nested enum (the full code provided in the link below).

public static class Foo {
    public enum Status {
        INITIAL, FINAL, DELETED, KEEP, EXCEPTION;
        
        public static Status parse(String str) {
            return Arrays.stream(values())
                .filter(cons -> cons.name().equalsIgnoreCase(str))
                .findFirst()
                .orElseThrow();
        }
    }
    
    private Status status;
    private int value1;
    private String value2;
    private LocalDateTime dateTime;
    
    public static Foo parse(List<String> strings, DateTimeFormatter formatter) {
        return new Foo(Status.parse(strings.get(0)),
            Integer.parseInt(strings.get(1)),
            strings.get(2),
            LocalDateTime.parse(strings.get(3), formatter));
    }
    
    // constructor, getters, etc.
}

Note: SimpleDateFormat class is legacy, the modern alternative is DateTimeFormatter.

main()

public static void main(String[] args) {
    List<List<String>> strings = List.of(
        List.of("Final", "331", "M", "22/03/2020 00:00:00"),
        List.of("Initial", "335", "M", "22/06/2022 00:00:00"),
        List.of("Exception", "335", "M", "22/05/2022 00:00:00"),
        List.of("Final", "335", "M", "20/06/2022 00:00:00"),
        List.of("Keep", "335", "M", "02/06/2022 11:00:00"),
        List.of("Final", "335", "M", "10/04/2022 02:00:00"),
        List.of("Deleted", "335", "M", "22/06/2022 15:55:10"),
        List.of("Exception", "335", "M", "22/06/2022 15:55:09"),
        List.of("Final", "335", "M", "22/06/2022 15:56:00"),
        List.of("Initial", "335", "M", "11/06/2022 00:00:00")
    );

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
    
    Comparator<Foo> byStatusByDate =
        Comparator.comparing(Foo::getStatus)
            .thenComparing(Foo::getDateTime);
    
    List<Foo> foos = strings.stream()           // Stream<List<String>>
        .map(list -> Foo.parse(list,formatter)) // Stream<Foo>
        .sorted(byStatusByDate)
        .collect(Collectors.toList());          // or .toList() for Java 16  
    
    foos.forEach(System.out::println); // printing the result
}

Output:

Foo{status=INITIAL, value1=335, value2='M', dateTime=2022-06-11T00:00}
Foo{status=INITIAL, value1=335, value2='M', dateTime=2022-06-22T00:00}
Foo{status=FINAL, value1=331, value2='M', dateTime=2020-03-22T00:00}
Foo{status=FINAL, value1=335, value2='M', dateTime=2022-04-10T02:00}
Foo{status=FINAL, value1=335, value2='M', dateTime=2022-06-20T00:00}
Foo{status=FINAL, value1=335, value2='M', dateTime=2022-06-22T15:56}
Foo{status=DELETED, value1=335, value2='M', dateTime=2022-06-22T15:55:10}
Foo{status=KEEP, value1=335, value2='M', dateTime=2022-06-02T11:00}
Foo{status=EXCEPTION, value1=335, value2='M', dateTime=2022-05-22T00:00}
Foo{status=EXCEPTION, value1=335, value2='M', dateTime=2022-06-22T15:55:09}

A link to Online Demo

CodePudding user response:

Try this.

static final List<String> definedOrder = List.of(
    "Initial","Final","Deleted","Keep","Exception");
static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
record Rec(int key0, Date key1, List<String> row) {}

static Date parseDate(String input) {
    try {
        return simpleDateFormat.parse(input);
    } catch (ParseException e) { throw new RuntimeException(e); }
}

public static void main(String[] args) {
    List<List<String>> outputToStore = Arrays.asList(
        Arrays.asList("Final", "331", "M", "22/03/2020 00:00:00"), 
        Arrays.asList("Initial", "335", "M", "22/06/2022 00:00:00"), 
        Arrays.asList("Exception", "335", "M", "22/05/2022 00:00:00"), 
        Arrays.asList("Final", "335", "M", "20/06/2022 00:00:00"), 
        Arrays.asList("Keep", "335", "M", "02/06/2022 11:00:00"), 
        Arrays.asList("Final", "335", "M", "10/04/2022 02:00:00"), 
        Arrays.asList("Deleted", "335", "M", "22/06/2022 15:55:10"),
        Arrays.asList("Exception", "335", "M", "22/06/2022 15:55:09"), 
        Arrays.asList("Final", "335", "M", "22/06/2022 15:56:00"), 
        Arrays.asList("Initial", "335", "M", "11/06/2022 00:00:00")
    );

    List<List<String>> sorted = outputToStore.stream()
        .map(e -> new Rec(definedOrder.indexOf(e.get(0)), parseDate(e.get(3)), e))
        .sorted(Comparator.comparingInt(Rec::key0).thenComparing(Rec::key1))
        .map(Rec::row)
        .toList();

    for (List<String> row : sorted)
        System.out.println(row);
}

output:

[Initial, 335, M, 11/06/2022 00:00:00]
[Initial, 335, M, 22/06/2022 00:00:00]
[Final, 335, M, 10/04/2022 02:00:00]
[Final, 335, M, 20/06/2022 00:00:00]
[Final, 331, M, 22/03/2020 00:00:00]
[Final, 335, M, 22/06/2022 15:56:00]
[Deleted, 335, M, 22/06/2022 15:55:10]
[Keep, 335, M, 02/06/2022 11:00:00]
[Exception, 335, M, 22/05/2022 00:00:00]
[Exception, 335, M, 22/06/2022 15:55:09]

CodePudding user response:

A map might be better to use for the predefined order and use LocalDateTime to compare by date. But else your were on the right track; you could just chain thenComparing to your Comparator :

Map<String,Integer> definedOrder = Map.of(
        "Initial", 1, "Final", 2, "Deleted", 3, "Keep", 4, "Exception", 5);

final DateTimeFormatter df = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");

outputToStore.sort(Comparator.comparing((List<String> list) -> definedOrder.get(list.get(0)))
        .thenComparing(Comparator.comparing(list -> LocalDateTime.parse(list.get(3), df)))
);
  • Related