gpt4 book ai didi

java - 使用 Java 8 流 API 创建字符串和排序列表的映射

转载 作者:行者123 更新时间:2023-11-30 06:40:51 25 4
gpt4 key购买 nike

我有以下类(class):

class Data {
String systemId;
String fileName;
int x;
int y;

Data(String systemId, String fileName, int x, int y) {
this.systemId = systemId;
this.fileName = fileName;
this.x = x;
this.y = y;
}
public String getSystemId() {
return systemId;
}

public void setSystemId(String systemId) {
this.systemId = systemId;
}

public String getFileName() {
return fileName;
}

public void setFileName(String fileName) {
this.fileName = fileName;
}

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}
}


class Result {
int x;
int y;

Result(int x, int y) {
this.x = x;
this.y = y;
}

public int getX() {
return x;
}

public void setX(int x) {
this.x = x;
}

public int getY() {
return y;
}

public void setY(int y) {
this.y = y;
}
}

List<Data> dataList = new ArrayList<>();
Data x1 = new Data("n1", "f1", 3, 4);
Data x2 = new Data("n1", "f1", 1, 2);
Data x3 = new Data("n1", "f1", 5, 6);
Data x4 = new Data("n1", "f2", 7, 8);
Data x5 = new Data("n2", "f1", 9, 10);
Data x6 = new Data("n2", "f2", 11, 12);
Data x7 = new Data("n3", "f1", 13, 14);
Data x8 = new Data("n4", "f1", 15, 16);
Data x9 = new Data("n1", "f1", 5, 10);
Data x10 = new Data("n1", "f1", 5, 2);

dataList.add(x1);dataList.add(x2);dataList.add(x3);dataList.add(x4);dataList.add(x5);dataList.add(x6);dataList.add(x7);dataList.add(x8);

我想使用 Java 流创建一个 Map<String, List<Result>>在给定的输入列表之外。此外,列表值需要根据字段(x 和 y)按升序排序

我需要输出图如下:

{"n1:f1" : [(1, 2), (3, 4), (5, 2), (5,6), (5,10)]
"n1:f2" : [(7, 8)]
"n2:f1" : [(9, 10)]
"n2:f2" : [(11, 12)]
"n3:f1" : [(13, 14)]
"n4:f1" : [(15, 16)]
}

映射的键是由冒号连接的 systemid 和文件名的组合。列表的值需要先按 x 排序,然后按 y 排序。

最佳答案

类似于:

Map<String, List<Result>> collect = dataList.stream()
.sorted(Comparator.comparing(Data::getX).thenComparing(Data::getY))
.collect(Collectors.groupingBy(d -> d.getSystemId() + ":" + d.getFileName(),
Collectors.mapping(d -> new Result(d.getX(), d.getY()), toList())));

关于java - 使用 Java 8 流 API 创建字符串和排序列表的映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56787096/

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