gpt4 book ai didi

java - 如何对多个元素上的 Vector> 进行排序,将子项分组在一起?

转载 作者:行者123 更新时间:2023-12-02 01:14:33 24 4
gpt4 key购买 nike

因此,我从 REST API 返回 JSON 数据,其中数据已按日期字段排序,然后添加到 JTable 中使用的 Vector> 中。我需要将具有相同 5 位数 key 的项目分组在一起,然后按附加标识符降序顺序 (3,2,1) 对这些项目进行排序,其中日期决定下一个 5 位数 key 是什么。

例如:

[[28696, 2, 11/15/19 17:57]]
[[28696, 1, 11/15/19 17:56]]
[[00972, 2, 11/15/19 17:55]]
[[28696, 3, 11/15/19 17:54]]
[[00972, 1, 11/15/19 17:53]]

应该是

[[28696, 3, 11/15/19 17:54]]
[[28696, 2, 11/15/19 17:57]]
[[28696, 1, 11/15/19 17:56]]
[[00972, 2, 11/15/19 17:55]]
[[00972, 1, 11/15/19 17:53]]

看到 28696 是该组中的第一个项目,也是整个数据集中最新的项目。

最佳答案

你想要的不是一个 sort 就能实现的手术。相反,您可以使用流来满足分组、组排序以及组内数据排序的要求。

首先请注意,我转换了您的 List<List<String>>进入List<Data> (根据 Max Vollmer 的建议)使其更易于使用和理解。如果您确实需要它作为 List您可以替换 DataList<String>Data.get??()List.get(?) :

public static void main(String[] args) throws IOException, TransformerException {
List<Data> list = Arrays.asList( //
new Data("28696", "2", "11/15/19 17:57"), //
new Data("28696", "1", "11/15/19 17:56"), //
new Data("00972", "2", "11/15/19 17:55"), //
new Data("28696", "3", "11/15/19 17:54"), //
new Data("00972", "1", "11/15/19 17:53"));

Comparator<Data> sortByTimestamp = Comparator.comparing(Data::getTimestamp).reversed();
Comparator<Data> sortByOccurrence = Comparator.comparing(Data::getOccurrence).reversed();

// LinkedHashMap keeps the insertion order
Collector<Data, ?, LinkedHashMap<String, List<Data>>> groupByIdKeepInsertOrder
= Collectors.groupingBy(Data::getId, LinkedHashMap::new, Collectors.toList());

List<Data> result = list.stream()
.sorted(sortByTimestamp) // sort all data by timestamp, if it's already sorted by timestamp you can skip this
.collect(groupByIdKeepInsertOrder) // group them by id keeping the timestamp order
.values().stream() // stream the lists of data grouped together
.peek(l -> l.sort(sortByOccurrence)) // sort each list of data by occurrence
.flatMap(Collection::stream) // flatten the lists into a single stream
.collect(Collectors.toList()); // collect all Data into a single list

System.out.println(result);
// [[28696, 3, 11/15/19 17:54],
// [28696, 2, 11/15/19 17:57],
// [28696, 1, 11/15/19 17:56],
// [00972, 2, 11/15/19 17:55],
// [00972, 1, 11/15/19 17:53]]
}
<小时/>
private static class Data {
private final String id;
private final String occurrence;
private final String timestamp;

public Data(String id, String occurrence, String timestamp) {
this.id = id;
this.occurrence = occurrence;
this.timestamp = timestamp;
}

public String getId() { return id; }
public String getOccurrence() { return occurrence; }
public String getTimestamp() { return timestamp; }
@Override public String toString() { return "[" + id + ", " + occurrence + ", " + timestamp + "]";}
}

关于java - 如何对多个元素上的 Vector<Vector<String>> 进行排序,将子项分组在一起?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58882996/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com