List<DeviceTransferEntity> allById = deviceTransferRepository.findAllById((Iterable<UUID>) deviceTransfer.getDeviceProfile().getId()); stream流得到Device的集合
时间: 2023-11-22 20:54:15 浏览: 76
可以使用Java 8的Stream API来对List进行操作,将List转换为Stream,然后使用map方法将每个DeviceTransferEntity对象转换为对应的Device对象,最后使用collect方法将结果收集到一个新的List中。示例代码如下:
```
List<DeviceTransferEntity> allById = deviceTransferRepository.findAllById((Iterable<UUID>) deviceTransfer.getDeviceProfile().getId());
List<Device> devices = allById.stream()
.map(DeviceTransferEntity::getDevice)
.collect(Collectors.toList());
```
其中,`DeviceTransferEntity::getDevice`是一个方法引用,表示调用`DeviceTransferEntity`对象的`getDevice`方法来获取对应的`Device`对象。`Collectors.toList()`方法用于将结果收集到一个新的List中。
相关问题
jdk8 优化以下代码: for (DqExecuteResult dqExecuteResult : dqExecuteResults) { String errorOutputPath = dqExecuteResult.getErrorOutputPath(); Path path = new Path(errorOutputPath); R<List<String>> getFileResult = resourceClient.getFilesAtPath(path.toUri().getPath()); if (null != getFileResult && getFileResult.isSuccess()) { for (String fullPath : getFileResult.getData()) { R<List<String>> previewResult = resourceClient.viewFileByPath(new Path(fullPath).toUri().getPath(), query.getCurrent(), query.getSize(), "\n"); if (null != previewResult && previewResult.isSuccess()) { if("原始库".equals(datasourceName)){ Long datasourceId = iDataSourceClient.queryRawDataSource().getId(); List<MetaColumn> tableColumns = iDataSourceMetaClient.getTableColumns(datasourceId, tableName); for (MetaColumn metaColumn : tableColumns){ headers.add(metaColumn.getColumnName()); } } else if("标准库".equals(datasourceName)){ Long datasourceId = iDataSourceClient.queryModelDataSource().getId(); List<MetaColumn> tableColumns = iDataSourceMetaClient.getTableColumns(datasourceId, tableName); for (MetaColumn metaColumn : tableColumns){ headers.add(metaColumn.getColumnName()); } } int headerSize = headers.size(); List<String> datas = previewResult.getData(); StringBuilder contextBuilder = new StringBuilder(); for(String data : datas){ contextBuilder.append(data.replaceAll("[\r\n\t]", " ")); contextBuilder.append("\n"); } StringReader reader = new StringReader(contextBuilder.toString()); Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader); for (CSVRecord record : records) { if (record.size() == headerSize){ List<String> content = new ArrayList<>(); for (String column : record) { content.add(column); } contents.add(content); } } } } } }
可以通过以下方式对代码进行优化:
1. 首先,可以将重复的代码段提取为一个方法,以便在两个 if 块中重用。例如:
```
private List<MetaColumn> getTableColumns(String datasourceName, String tableName) {
Long datasourceId;
if ("原始库".equals(datasourceName)) {
datasourceId = iDataSourceClient.queryRawDataSource().getId();
} else if ("标准库".equals(datasourceName)) {
datasourceId = iDataSourceClient.queryModelDataSource().getId();
}
return iDataSourceMetaClient.getTableColumns(datasourceId, tableName);
}
```
2. 其次,可以将 CSV 解析和数据处理逻辑提取为一个方法:
```
private List<List<String>> processCSVData(List<String> datas, List<String> headers) throws IOException {
int headerSize = headers.size();
List<List<String>> contents = new ArrayList<>();
StringBuilder contextBuilder = new StringBuilder();
for (String data : datas) {
contextBuilder.append(data.replaceAll("[\r\n\t]", " "));
contextBuilder.append("\n");
}
StringReader reader = new StringReader(contextBuilder.toString());
Iterable<CSVRecord> records = CSVFormat.DEFAULT.parse(reader);
for (CSVRecord record : records) {
if (record.size() == headerSize) {
List<String> content = new ArrayList<>();
for (String column : record) {
content.add(column);
}
contents.add(content);
}
}
return contents;
}
```
3. 然后,可以使用 Java 8 的 Lambda 表达式和方法引用来简化代码。例如:
```
dqExecuteResults.stream()
.map(DqExecuteResult::getErrorOutputPath)
.map(Path::new)
.map(Path::toUri)
.map(URI::getPath)
.map(resourceClient::getFilesAtPath)
.filter(Objects::nonNull)
.filter(R::isSuccess)
.flatMap(result -> result.getData().stream())
.map(Path::new)
.map(Path::toUri)
.map(URI::getPath)
.map(fullPath -> resourceClient.viewFileByPath(fullPath, query.getCurrent(), query.getSize(), "\n"))
.filter(Objects::nonNull)
.filter(R::isSuccess)
.flatMap(result -> {
List<String> datas = result.getData();
List<String> headers = new ArrayList<>();
if ("原始库".equals(datasourceName) || "标准库".equals(datasourceName)) {
getTableColumns(datasourceName, tableName).stream()
.map(MetaColumn::getColumnName)
.forEach(headers::add);
}
try {
return processCSVData(datas, headers).stream();
} catch (IOException e) {
e.printStackTrace();
return Stream.empty();
}
})
.forEach(contents::add);
```
这段代码使用了 stream 操作来简化循环和条件语句,使用方法引用、Lambda 表达式和函数式接口来写出更简洁的代码。
SingleOutputStreamOperator<List<JSONObject>> applyDataStream = dataStreamSource.keyBy(value -> { String[] splitValues = value.getString("key").toString().split(":"); return splitValues[2]; }).window(TumblingProcessingTimeWindows.of(Time.seconds(2))).apply(new WindowFunction<JSONObject, List<JSONObject>, String, TimeWindow>() { @Override public void apply(String key, TimeWindow timeWindow, Iterable<JSONObject> input, Collector<List<JSONObject>> out) throws Exception { List<JSONObject> output = new ArrayList<>(); input.forEach(s -> { // String topicName = ModelUtil.getConfigValue("ods_kafka_all_data_topicName") + "_" + key; //主题名称 String value = s.getString("value"); TranslateJson translateJson = JSON.parseObject(value, TranslateJson.class); if ("read".equals(translateJson.getType()) || "c".equals(translateJson.getType())) {//新增的数据才同步 使用这种写法优化上面代码
您可以使用 Lambda 表达式来优化上面的代码,示例代码如下:
```
SingleOutputStreamOperator<List<JSONObject>> applyDataStream = dataStreamSource
.keyBy(value -> value.getString("key").toString().split(":")[2])
.window(TumblingProcessingTimeWindows.of(Time.seconds(2)))
.apply((String key, TimeWindow timeWindow, Iterable<JSONObject> input, Collector<List<JSONObject>> out) -> {
List<JSONObject> output = new ArrayList<>();
input.forEach(s -> {
String value = s.getString("value");
TranslateJson translateJson = JSON.parseObject(value, TranslateJson.class);
if ("read".equals(translateJson.getType()) || "c".equals(translateJson.getType())) {
// 新增的数据才同步
// String topicName = ModelUtil.getConfigValue("ods_kafka_all_data_topicName") + "_" + key; //主题名称
output.add(s);
}
});
out.collect(output);
});
```
使用 Lambda 表达式可以使代码更加简洁易读,同时也可以提高代码的执行效率。
阅读全文