Java 从列表<Object[]> 流式传输到列表<MyDTO>
Java Stream from List<Object[]> to a List<MyDTO>
我有一个 List<Object[]>
,其中 Object[]
的大小为 3
并且来自查询。查询结果如下:
| vehicleId | modelId | serviceId |
|------------------------------------|---------|-----------------|
|93bf3e92-7a37-4e23-836d-eed5a104341f| 214|80a7-ce5640b18879|
|b4066520-e127-44b7-bcc0-1d1187de559c| 214|80a7-ce5640b18879|
|ae6cb0fe-1501-4311-a2b4-cfb8b4f51ca4| 214|80a7-ce5640b18879|
|cf80ff11-6e23-4c19-8b6d-55d34d131566| 214|80a7-ce5640b18879|
它应该映射在下面的列表中。第二列和最后一列将映射到 modelId 和 serviceId,而第一列应成为 vehicleIds 列表。
我需要将其映射到 List<MyDTO>
,其中 MyDTO
如下所示:
MyDTO{
// constructor
MyDTO(String modelId, String serviceId, List<String> vehicleIds){...}
String modelId;
String serviceId;
List<String> vehicleIds;
}
我正在尝试弄清楚如何在流中分组,但似乎没有结果。这就是我被屏蔽的地方...
listOfObjectArrays.stream()
.map(objects -> new MyDTO((String) objects[0], (String) objects[1], null));
无法弄清楚如何应用完成这项工作的减少操作,非常感谢任何帮助!
编辑:
抱歉,我忘了说我坚持使用 Java 8。谢谢大家的精彩回答。
您可以通过按 modelId
分组数据然后使用 groupingBy()
和 mapping()
收集器 serviceId
来创建嵌套中间地图。
然后在条目集上创建一个流。并根据 modelId
和 serviceId
.
的每个组合展平每个内部映射创建 new MyDTO
Map<String, Map<String, List<String>>> vehicleIdByModelIdAndServiceId =
listOfObjectArrays.stream()
.collect(Collectors.groupingBy(objects -> (String) objects[1],
Collectors.groupingBy(objects -> (String) objects[2],
Collectors.mapping(objects -> (String) objects[0],
Collectors.toList()))));
List<MyDTO> result = vehicleIdByModelIdAndServiceId.entrySet().stream()
.flatMap(baseEntry -> baseEntry.getValue().entrySet().stream()
.map(entry -> new MyDTO(baseEntry.getKey(), entry.getKey(), entry.getValue())))
.collect(Collectors.toList());
另一种选择是在中间映射中使用 Map.Entry
作为键,值将是 vehicleId
.
的列表
List<MyDTO> result = listOfObjectArrays.stream()
.collect(Collectors.groupingBy(objects -> new AbstractMap.SimpleEntry<>((String) objects[1], (String) objects[2]),
Collectors.mapping(objects -> (String) objects[0],
Collectors.toList())))
.entrySet().stream()
.map(entry -> new MyDTO(entry.getKey().getKey(),
entry.getKey().getValue(),
entry.getValue()))
.collect(Collectors.toList());
这需要一个 Collectors.groupBy() 函数,因为您要获取流并将它们组合在一起。
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class F {
public static void main(String[] args) {
var in = List.of(new Object[]{"93bf3e92-7a37-4e23-836d-eed5a104341f", "214", "80a7-ce5640b18879"},
new Object[]{"b4066520-e127-44b7-bcc0-1d1187de559c", "214", "80a7-ce5640b18879"},
new Object[]{"b4066520-e127-44b7-bcc0-dddddddddddd", "215", "80a7-ce5640b18879"}
);
Map<Key, List<MyDTOOne>> p1 =
in.stream()
.map(objs -> new String[]{(String) objs[0], (String) objs[1], (String) objs[2]})
.map(objs -> new MyDTOOne(objs[1], objs[2], objs[0]))
.collect(Collectors.groupingBy(myDTO -> new Key(myDTO.modelId, myDTO.serviceId)));
List<MyDTO> p2 = p1.entrySet()
.stream()
.map(e -> new MyDTO(e.getKey().modelId, e.getKey().serviceId, e.getValue().stream().map(MyDTOOne::vehicleId).toList()))
.toList();
System.out.println(p2);
}
static record Key(String modelId, String serviceId) {
}
static record MyDTO(String modelId, String serviceId, List<String> vehicleIds) {
}
static record MyDTOOne(String modelId, String serviceId, String vehicleId) {
}
}
Java 8
您可以先将它们全部映射到字符串,然后按元组 (modelId, serviceId) 进行分组,然后才将分组结果映射到 dtos。
import java.util.Arrays;
import java.util.stream.Collectors;
List<MyDto> myDtos = queryResult.stream()
// cast all to String and put into tuple
.map(objects -> Arrays.asList((String) objects[0], (String) objects[1], (String) objects[2]))
// group by tuple (modelid, serviceId)
.collect(Collectors.groupingBy(r -> Arrays.asList(r.get(1), r.get(2)),
Collectors.mapping(r -> r.get(0), Collectors.toList())))
.entrySet().stream()
.map(entry -> new MyDto(entry.getKey().get(0), entry.getKey().get(1), entry.getValue()))
.collect(Collectors.toList());
奖励积分 Java 14+
为了提高可读性而不是使用列表,我们引入了记录
import java.util.List;
import java.util.Map;
record MyDto(String vehicleId, String modelId, List<String> serviceIds) {
public MyDto(Map.Entry<AggregateKey, List<String>> vehiclesAggregate) {
this(vehiclesAggregate.getKey().modelId(), vehiclesAggregate.getKey().serviceId(),vehiclesAggregate.getValue());
}
}
record ResultRow(String vehicleId, String modelId, String serviceId) {
public ResultRow(Object[] entries) {
this((String) entries[0], (String) entries[1], (String) entries[2]);
}
public AggregateKey getKey() {
return new AggregateKey(modelId, serviceId);
}
}
record AggregateKey(String modelId, String serviceId) {}
导致更短且可读性更强的流式传输管道
import java.util.List;
import java.util.stream.Collectors;
List<MyDto> myDtos = queryResult.stream()
.map(ResultRow::new)
.collect(Collectors.groupingBy(ResultRow::getKey,
Collectors.mapping(ResultRow::vehicleId, Collectors.toList())))
.entrySet().stream()
.map(MyDto::new)
.toList(); // shorthand for collect(Collectors.toList) since Java 16
如果您不一定需要使用stream
,您可以随时使用标准循环,例如:
Map<String, MyDTO> myDTOs = new HashMap<>();
for(Object[] a : listOfObjectArrays) {
String key = a[1] + " - " + a[2];
MyDTO myDTO = myDTOs.get(key);
if(myDTO == null) {
List<String> vehicleIds = new ArrayList<>();
vehicleIds.add((String) a[0]);
myDTO = new MyDTO((String) a[1], (String) a[2], vehicleIds);
myDTOs.put(key, myDTO);
} else {
myDTO.getVehicleIds().add((String) a[0]);
}
}
List<MyDTO> myDTOList = new ArrayList<>(myDTOs.values());
想法是
- 串流
Object[]
为 {String,Long,String}
- 分组依据
{Object[1],Object[2]}
;收集(不同 Object[0]
)
Map<List<Object[0]>,{Object[1],Object[2]}>
--> List<MyDto>
为此,我设置了两个支持 classes,其中一个是您提供的,另一个需要作为 groupingBuy
工作的密钥:
class MyDTO{
String modelId;
String serviceId;
List<String> vehicleIds;
MyDTO(String modelId, String serviceId, String vehicleId) {
// Need to put in a Modifiable ArrayList so the reduce can happen
this(modelId,serviceId,new ArrayList<>(List.of(vehicleId)));
}
MyDTO(String modelId, String serviceId, List<String> vehicleIds){
this.modelId = modelId;
this.serviceId = serviceId;
this.vehicleIds = vehicleIds;
}
public MyDTOKey getKey() {
return new MyDTOKey(modelId, serviceId);
}
public MyDTO reduce(MyDTO other) {
this.vehicleIds.addAll(other.vehicleIds);
return this;
}
public void dump() {
System.out.println("modelId: "+modelId+"; serviceId: "+serviceId+"; vehicleIds: "+vehicleIds.toString());
}
}
private class MyDTOKey<T1,T2> {
T1 v1;
T2 v2;
public MyDTOKey(T1 v1,T2 v2) {
this.v1 = v1;
this.v2 = v2;
}
@Override
public int hashCode() {
return Objects.hash(v1,v2);
}
/*
* Required for the groupby to work correctly as it
* doesnt automatically on an Object[]
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MyDTOKey <?, ?> other = (MyDTOKey <?, ?>) obj;
if (!Objects.equals(this.v1, other.v1)) {
return false;
}
return Objects.equals(this.v2, other.v2);
}
}
使用 heads-on 方法,我可以构建这样的东西:
List<Object []> data = List.of(
new Object[]{"93bf3e92-7a37-4e23-836d-eed5a104341f", "214", "80a7-ce5640b18879"},
new Object[]{"b4066520-e127-44b7-bcc0-1d1187de559c", "214", "80a7-ce5640b18879"},
new Object[]{"b4066520-e127-44b7-bcc0-dddddddddddd", "215", "80a7-ce5640b18879"}
);
public static void main(String [] pars) {
Map<Pair<String,String>,List<String>> map = data
.stream()
.collect(groupingBy(
o->new MyDTOKey((String)o[1],(String)o[2]), // group by last two only
mapping(
o->(String)o[0], // Collapse the vehicle id's to a list
toList() // Using set to take out duplicate vehicle id's
)
));
// Convert the map to a List.
List<MyDTO> dtos = map.entrySet().stream()
.map(e->new MyDTO(e.getKey().v1,e.getKey().v2,e.getValue()))
.collect(toList());
for (MyDTO dto:dtos) {
dto.dump();
}
}
创建 class 来表示元组 (MyDTOKey
) 的全部工作可以通过将其设置为 List<String>
来避免,就像在@Valerij Doblers 的回答中所做的那样。
但是已经对 MyDTO
class 做了一些小的调整,我们也可以将其重写如下:
public static void main(String [] pars) {
List<MyDTO> data = List.of(
new MyDTO("214", "80a7-ce5640b18879","93bf3e92-7a37-4e23-836d-eed5a104341f"),
new MyDTO("214", "80a7-ce5640b18879","b4066520-e127-44b7-bcc0-1d1187de559c"),
new MyDTO("215", "80a7-ce5640b18879","b4066520-e127-44b7-bcc0-dddddddddddd")
);
List<MyDTO> dtos = data.stream()
.collect(
groupingBy(
MyDTO::getKey,
reducing(MyDTO::reduce)
)
) // Produces a Map<MyDTOKey,MyDTO>
.values().stream() // Streams Optional<MyDTO>
.flatMap(o->o.stream()) // expand to contained MyDTO
.collect(toList())
;
for (MyDTO dto:dtos) {
dto.dump();
}
}
也许再努力一点,我们可以直接在 List 中收集,而无需先通过 Map。
我有一个 List<Object[]>
,其中 Object[]
的大小为 3
并且来自查询。查询结果如下:
| vehicleId | modelId | serviceId |
|------------------------------------|---------|-----------------|
|93bf3e92-7a37-4e23-836d-eed5a104341f| 214|80a7-ce5640b18879|
|b4066520-e127-44b7-bcc0-1d1187de559c| 214|80a7-ce5640b18879|
|ae6cb0fe-1501-4311-a2b4-cfb8b4f51ca4| 214|80a7-ce5640b18879|
|cf80ff11-6e23-4c19-8b6d-55d34d131566| 214|80a7-ce5640b18879|
它应该映射在下面的列表中。第二列和最后一列将映射到 modelId 和 serviceId,而第一列应成为 vehicleIds 列表。
我需要将其映射到 List<MyDTO>
,其中 MyDTO
如下所示:
MyDTO{
// constructor
MyDTO(String modelId, String serviceId, List<String> vehicleIds){...}
String modelId;
String serviceId;
List<String> vehicleIds;
}
我正在尝试弄清楚如何在流中分组,但似乎没有结果。这就是我被屏蔽的地方...
listOfObjectArrays.stream()
.map(objects -> new MyDTO((String) objects[0], (String) objects[1], null));
无法弄清楚如何应用完成这项工作的减少操作,非常感谢任何帮助!
编辑: 抱歉,我忘了说我坚持使用 Java 8。谢谢大家的精彩回答。
您可以通过按 modelId
分组数据然后使用 groupingBy()
和 mapping()
收集器 serviceId
来创建嵌套中间地图。
然后在条目集上创建一个流。并根据 modelId
和 serviceId
.
new MyDTO
Map<String, Map<String, List<String>>> vehicleIdByModelIdAndServiceId =
listOfObjectArrays.stream()
.collect(Collectors.groupingBy(objects -> (String) objects[1],
Collectors.groupingBy(objects -> (String) objects[2],
Collectors.mapping(objects -> (String) objects[0],
Collectors.toList()))));
List<MyDTO> result = vehicleIdByModelIdAndServiceId.entrySet().stream()
.flatMap(baseEntry -> baseEntry.getValue().entrySet().stream()
.map(entry -> new MyDTO(baseEntry.getKey(), entry.getKey(), entry.getValue())))
.collect(Collectors.toList());
另一种选择是在中间映射中使用 Map.Entry
作为键,值将是 vehicleId
.
List<MyDTO> result = listOfObjectArrays.stream()
.collect(Collectors.groupingBy(objects -> new AbstractMap.SimpleEntry<>((String) objects[1], (String) objects[2]),
Collectors.mapping(objects -> (String) objects[0],
Collectors.toList())))
.entrySet().stream()
.map(entry -> new MyDTO(entry.getKey().getKey(),
entry.getKey().getValue(),
entry.getValue()))
.collect(Collectors.toList());
这需要一个 Collectors.groupBy() 函数,因为您要获取流并将它们组合在一起。
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
class F {
public static void main(String[] args) {
var in = List.of(new Object[]{"93bf3e92-7a37-4e23-836d-eed5a104341f", "214", "80a7-ce5640b18879"},
new Object[]{"b4066520-e127-44b7-bcc0-1d1187de559c", "214", "80a7-ce5640b18879"},
new Object[]{"b4066520-e127-44b7-bcc0-dddddddddddd", "215", "80a7-ce5640b18879"}
);
Map<Key, List<MyDTOOne>> p1 =
in.stream()
.map(objs -> new String[]{(String) objs[0], (String) objs[1], (String) objs[2]})
.map(objs -> new MyDTOOne(objs[1], objs[2], objs[0]))
.collect(Collectors.groupingBy(myDTO -> new Key(myDTO.modelId, myDTO.serviceId)));
List<MyDTO> p2 = p1.entrySet()
.stream()
.map(e -> new MyDTO(e.getKey().modelId, e.getKey().serviceId, e.getValue().stream().map(MyDTOOne::vehicleId).toList()))
.toList();
System.out.println(p2);
}
static record Key(String modelId, String serviceId) {
}
static record MyDTO(String modelId, String serviceId, List<String> vehicleIds) {
}
static record MyDTOOne(String modelId, String serviceId, String vehicleId) {
}
}
Java 8
您可以先将它们全部映射到字符串,然后按元组 (modelId, serviceId) 进行分组,然后才将分组结果映射到 dtos。
import java.util.Arrays;
import java.util.stream.Collectors;
List<MyDto> myDtos = queryResult.stream()
// cast all to String and put into tuple
.map(objects -> Arrays.asList((String) objects[0], (String) objects[1], (String) objects[2]))
// group by tuple (modelid, serviceId)
.collect(Collectors.groupingBy(r -> Arrays.asList(r.get(1), r.get(2)),
Collectors.mapping(r -> r.get(0), Collectors.toList())))
.entrySet().stream()
.map(entry -> new MyDto(entry.getKey().get(0), entry.getKey().get(1), entry.getValue()))
.collect(Collectors.toList());
奖励积分 Java 14+
为了提高可读性而不是使用列表,我们引入了记录
import java.util.List;
import java.util.Map;
record MyDto(String vehicleId, String modelId, List<String> serviceIds) {
public MyDto(Map.Entry<AggregateKey, List<String>> vehiclesAggregate) {
this(vehiclesAggregate.getKey().modelId(), vehiclesAggregate.getKey().serviceId(),vehiclesAggregate.getValue());
}
}
record ResultRow(String vehicleId, String modelId, String serviceId) {
public ResultRow(Object[] entries) {
this((String) entries[0], (String) entries[1], (String) entries[2]);
}
public AggregateKey getKey() {
return new AggregateKey(modelId, serviceId);
}
}
record AggregateKey(String modelId, String serviceId) {}
导致更短且可读性更强的流式传输管道
import java.util.List;
import java.util.stream.Collectors;
List<MyDto> myDtos = queryResult.stream()
.map(ResultRow::new)
.collect(Collectors.groupingBy(ResultRow::getKey,
Collectors.mapping(ResultRow::vehicleId, Collectors.toList())))
.entrySet().stream()
.map(MyDto::new)
.toList(); // shorthand for collect(Collectors.toList) since Java 16
如果您不一定需要使用stream
,您可以随时使用标准循环,例如:
Map<String, MyDTO> myDTOs = new HashMap<>();
for(Object[] a : listOfObjectArrays) {
String key = a[1] + " - " + a[2];
MyDTO myDTO = myDTOs.get(key);
if(myDTO == null) {
List<String> vehicleIds = new ArrayList<>();
vehicleIds.add((String) a[0]);
myDTO = new MyDTO((String) a[1], (String) a[2], vehicleIds);
myDTOs.put(key, myDTO);
} else {
myDTO.getVehicleIds().add((String) a[0]);
}
}
List<MyDTO> myDTOList = new ArrayList<>(myDTOs.values());
想法是
- 串流
Object[]
为{String,Long,String}
- 分组依据
{Object[1],Object[2]}
;收集(不同Object[0]
) Map<List<Object[0]>,{Object[1],Object[2]}>
-->List<MyDto>
为此,我设置了两个支持 classes,其中一个是您提供的,另一个需要作为 groupingBuy
工作的密钥:
class MyDTO{
String modelId;
String serviceId;
List<String> vehicleIds;
MyDTO(String modelId, String serviceId, String vehicleId) {
// Need to put in a Modifiable ArrayList so the reduce can happen
this(modelId,serviceId,new ArrayList<>(List.of(vehicleId)));
}
MyDTO(String modelId, String serviceId, List<String> vehicleIds){
this.modelId = modelId;
this.serviceId = serviceId;
this.vehicleIds = vehicleIds;
}
public MyDTOKey getKey() {
return new MyDTOKey(modelId, serviceId);
}
public MyDTO reduce(MyDTO other) {
this.vehicleIds.addAll(other.vehicleIds);
return this;
}
public void dump() {
System.out.println("modelId: "+modelId+"; serviceId: "+serviceId+"; vehicleIds: "+vehicleIds.toString());
}
}
private class MyDTOKey<T1,T2> {
T1 v1;
T2 v2;
public MyDTOKey(T1 v1,T2 v2) {
this.v1 = v1;
this.v2 = v2;
}
@Override
public int hashCode() {
return Objects.hash(v1,v2);
}
/*
* Required for the groupby to work correctly as it
* doesnt automatically on an Object[]
*/
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final MyDTOKey <?, ?> other = (MyDTOKey <?, ?>) obj;
if (!Objects.equals(this.v1, other.v1)) {
return false;
}
return Objects.equals(this.v2, other.v2);
}
}
使用 heads-on 方法,我可以构建这样的东西:
List<Object []> data = List.of(
new Object[]{"93bf3e92-7a37-4e23-836d-eed5a104341f", "214", "80a7-ce5640b18879"},
new Object[]{"b4066520-e127-44b7-bcc0-1d1187de559c", "214", "80a7-ce5640b18879"},
new Object[]{"b4066520-e127-44b7-bcc0-dddddddddddd", "215", "80a7-ce5640b18879"}
);
public static void main(String [] pars) {
Map<Pair<String,String>,List<String>> map = data
.stream()
.collect(groupingBy(
o->new MyDTOKey((String)o[1],(String)o[2]), // group by last two only
mapping(
o->(String)o[0], // Collapse the vehicle id's to a list
toList() // Using set to take out duplicate vehicle id's
)
));
// Convert the map to a List.
List<MyDTO> dtos = map.entrySet().stream()
.map(e->new MyDTO(e.getKey().v1,e.getKey().v2,e.getValue()))
.collect(toList());
for (MyDTO dto:dtos) {
dto.dump();
}
}
创建 class 来表示元组 (MyDTOKey
) 的全部工作可以通过将其设置为 List<String>
来避免,就像在@Valerij Doblers 的回答中所做的那样。
但是已经对 MyDTO
class 做了一些小的调整,我们也可以将其重写如下:
public static void main(String [] pars) {
List<MyDTO> data = List.of(
new MyDTO("214", "80a7-ce5640b18879","93bf3e92-7a37-4e23-836d-eed5a104341f"),
new MyDTO("214", "80a7-ce5640b18879","b4066520-e127-44b7-bcc0-1d1187de559c"),
new MyDTO("215", "80a7-ce5640b18879","b4066520-e127-44b7-bcc0-dddddddddddd")
);
List<MyDTO> dtos = data.stream()
.collect(
groupingBy(
MyDTO::getKey,
reducing(MyDTO::reduce)
)
) // Produces a Map<MyDTOKey,MyDTO>
.values().stream() // Streams Optional<MyDTO>
.flatMap(o->o.stream()) // expand to contained MyDTO
.collect(toList())
;
for (MyDTO dto:dtos) {
dto.dump();
}
}
也许再努力一点,我们可以直接在 List 中收集,而无需先通过 Map。