按日期属性排序对象列表

时间:2018-11-29 14:22:49

标签: java sorting localdate

我有一个包含两个LocalDate属性的对象:

public class SomeObject {
    private LocalDate startDate;
    private LocalDate endDate;
}

为简洁起见,省略了构造函数和其他内容。我想按它们的开始日期对这些对象的列表进行排序,然后将下一个对象的开始日期分配给上一个对象的结束日期。为了澄清,我从这些对象的列表开始:

SomeObject object1 = new SomeObject(LocalDate.parse("2015-01-01"), null);
SomeObject object2 = new SomeObject(LocalDate.parse("2014-01-01"), null);
SomeObject object3 = new SomeObject(LocalDate.parse("2016-01-01"), null);

List<SomeObject> list = Arrays.asList(object1, object2, object3);

排序后应返回:

for (SomeObject object : list) {
    System.out.println(object.startDate.toString() + " " + object.endDate.toString() );
}

2014-01-01 2015-01-01
2015-01-01 2016-01-01
2016-01-01 null

每个列表最多只包含3个或4个这些对象,但是代码可能必须处理成千上万个这样的列表,所以我正在寻找一种有效的方法来实现此目的。

4 个答案:

答案 0 :(得分:3)

您可以将Collections.sort与Comparator一起使用。在带有Lambdas的Java 8中,它看起来像这样:

    Collections.sort(list, (x, y) -> x.startDate.compareTo(y.startDate));

    for (int i = 0; i < (list.size() - 1); i++) {
        list.get(i).endDate = list.get(i + 1).startDate;
    }

答案 1 :(得分:0)

利用LocalDate已经implements Comparable的事实,并让您的SomeObject做同样的事情。另外,给它一个适当的toString()方法,该方法可以处理null值,以便将您的对象表示为String

public class SomeObject implements Comparable<SomeObject> {
    private LocalDate startDate;
    private LocalDate endDate;

    public SomeObject(LocalDate startDate, LocalDate endDate) {
        this.startDate = startDate;
        this.endDate = endDate;
    }

    @Override
    public int compareTo(SomeObject anotherObject) {
        return this.startDate.compareTo(anotherObject.startDate);
    }

    @Override
    public String toString() {
        String start = startDate == null ? "null" : startDate.format(DateTimeFormatter.ISO_LOCAL_DATE);
        String end = endDate == null ? "null" : endDate.format(DateTimeFormatter.ISO_LOCAL_DATE); 
        StringBuilder sb = new StringBuilder();
        sb.append(start).append(" ").append(end);
        return sb.toString();
    }
}

这样做,您可以轻松地调用Collections.sort(list);并按startDate对数据进行排序:

public class SomeObjectSorting {

    public static void main(String[] args) {
        SomeObject object1 = new SomeObject(LocalDate.parse("2015-01-01"), null);
        SomeObject object2 = new SomeObject(LocalDate.parse("2014-01-01"), LocalDate.parse("2017-01-01"));
        SomeObject object3 = new SomeObject(LocalDate.parse("2016-01-01"), null);

        List<SomeObject> list = Arrays.asList(object1, object2, object3);

        System.out.println("———— BEFORE SORTING ————");

        list.forEach(object -> {
            System.out.println(object.toString());
        });

        Collections.sort(list);

        System.out.println("———— AFTER SORTING ————");

        list.forEach(object -> {
            System.out.println(object.toString());
        });
    }
}

答案 2 :(得分:0)

正如您所提到的,您实际上并不在乎它是startDate还是endDate,只需订购所有这些,也许以下内容对您有帮助:

List<LocalDate> dates = list.stream()
        .flatMap(s -> Stream.of(s.startDate, s.endDate))
        .filter(Objects::nonNull) // maybe... if nulls are required too, then skip that part here... (but also check the sorting variant then); note that I use null now if the last date is reached (check the printing part for that)
        .distinct()
        .sorted()                 // natural order
        // alternatively: natural order + nulls last
        // .sorted(Comparator.nullsLast(Comparator.comparing(Function.identity())))
        .collect(Collectors.toList());

// printing part:
IntStream.range(0, dates.size())
        .mapToObj(i -> {
            String from = Objects.toString(dates.get(i));
            String upto = Objects.toString(i < dates.size() - 1 ? dates.get(i + 1) : null); // exchange null with the end date you are expecting
            return from + " - " + upto;
        })
        .forEach(System.out::println);

编辑:之前,您的一个示例上已经设置了endDate,因为现在不再如此了,这里更新了如何设置正确的日期范围。基本上与Ralf Renz在回答中使用的类似:

list.sort(Comparator.comparing(SomeObject::getStartDate));
IntStream.range(0, list.size() - 1)
         .forEach(i -> list.get(i).endDate = list.get(i + 1).startDate);
// or if you care about performance, just do the same as Ralf did:
for (int i = 0; i < (list.size() - 1); i++) {
    list.get(i).endDate = list.get(i + 1).startDate;
}

答案 3 :(得分:0)

作为已接受答案的增强:

Collections.sort(list, Comparator.comparing(SomeObject::getStartDate);