gpt4 book ai didi

java - 使用java 8转换为map(拆分spring并制作key,对象的其他值作为value)

转载 作者:行者123 更新时间:2023-12-01 18:11:11 27 4
gpt4 key购买 nike

我的Order类如下:

class Order {
String orderId;
String executionId;

Order(String orderId, String executionId) {
this.orderId = orderId;
this.executionId = executionId;
}

public String getOrderId() {
return orderId;
}

public void setOrderId(String orderId) {
this.orderId = orderId;
}

public String getExecutionId() {
return executionId;
}

public void setExecutionId(String executionId) {
this.executionId = executionId;
}
}
List<Order> orders =
Arrays.asList( new Order("2", "23,21,25"),
new Order("4", "22,24"),
new Order("6", "27"),
new Order("2", "28,30"),
new Order("4", "29"),
new Order("5", "26"));

我需要根据以下结构输出一个map对象来获取与执行相关的订单

Map<String, String> = {"23","2"},{"21","2"},{"25","2"},{"22","4"},{"24","4"},{"27","6"},{"28","2"},{"30","2"},{"29","4"},{"26","5"};

逗号分隔的值应被视为映射键,对象的其他值应被视为值。

最佳答案

我会选择像下面这样的东西 -

    Map<String, String> flatMap = new HashMap<>();

orders.forEach(order -> {
String k = order.orderId;
String values = order.executionId;

for (String v : values.split(",")) {
flatMap.put(v, k);
}

});

不是单行的方法,但我更喜欢可读性。

这是不太受欢迎的方法 -

Map<String, String> flatMap = orders.stream()
.map(order -> Arrays.stream(order.executionId.split(","))
.collect(Collectors.toMap(Function.identity(), x -> order.orderId)))
.flatMap(map -> map.entrySet().stream())
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

关于java - 使用java 8转换为map(拆分spring并制作key,对象的其他值作为value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60466566/

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