对两个元素进行嵌套列表

发布于 2025-02-13 23:38:43 字数 1874 浏览 0 评论 0原文

我有一个嵌套列表,名为outputtostore其内容以下给出:

[[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]]

我需要基于2条条件进行对此进行排序:第一个是自定义订单:“初始” “,“ final”,“删除”,“ keep”,“异常” ,然后基于 dateTime

我能够做到这一点,但不确定这是做到这一点的最佳方法。

我的代码:

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;
});

我得到了所需的结果:

[[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]]

但是有什么更好或简洁的方法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

红焚 2025-02-20 23:38:43

使用对象的力量

以您表示数据的方式

,不方便且容易出错。显然,它必须是具有适当类型的属性,而不是字符串列表。 滥用集合的,

它是使用String作为数字,日期等的类型 这并不能带来任何优势。除了在控制台上打印外,您无需分析字符串就无能为力。正确的数据类型使您可以访问其字符串无法为您提供的独特行为。

第一个属性,我们称其为状态可能是 enum enum - 是一种特殊的类,当您需要代表有限的价值观时,它们非常方便,并且它们具有自然顺序,这与 enum-constants 的顺序(已声明的顺序)。

为了表示日期时间信息,我们可以使用java.time软件包中的Java 8类之一。在下面的示例中,我将使用localdateTime(类date是遗产,避免使用它)。

这样的类的外观是:

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.
}

使用Java 8构建比较器

,以便对foo对象的列表进行排序,我们需要定义比较器。

为此,我们可以使用比较器与Java 8的接口中引入的静态方法。我们可以流利的方式链接这些方法,因为它们都提供了一个比较器。

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

注意:我们需要在A 单个比较器中定义排序逻辑。不要像您在代码中完成的两次数据对数据进行排序,它会导致不必要的性能开销。

要了解如何使用Java-8方法构建比较器,请查看 教程

为了排序foo对象的列表,我们可以使用方法list.sort(),该是在Java 9中引入的,作为collections.sort的更流利的替代方案。 ()

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

解析数据

如果数据作为字符串的集合来

,则需要对其进行解析。为此,我们需要增强foo及其嵌套 enum (下面的链接中提供的完整代码)。

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.
}

注意: SimpleDateFormat类是遗产,现代替代方案是 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
}

输出:

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链接在线演示

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 limited set of values, and they have a natural order, that is the same as the order of the enum-constants (the order in which they have been declared).

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 (class Date is legacy, avoid using it).

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 strings, 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

回首观望 2025-02-20 23:38:43

尝试一下。

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);
}

输出:

[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]

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]
千纸鹤 2025-02-20 23:38:43

地图可能更好地用于预定义订单,并使用localdateTime按日期进行比较。但否则你走在正确的道路上;您可以将链条链接到比较器:

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)))
);

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)))
);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文