我被困在一个对象的子数组中拆分数组。我有以下内容:
输入/输出AClass:
{
attribute1: 'value1',
attribute2: 'value2',
// etc.
assets: [
{assetAttribute1: 'value1', // etc.},
{assetAttribute2: 'value2', // etc.}
// etc.
]
}
流输入:
inputs = [
{
attribute1: 'value1',
attribute2: 'value2',
assets: [
{assetAttribute1: 'value1', // etc.},
{assetAttribute2: 'value2', // etc.}
// etc.
]
},
]
预期的流输出:
outputs = [
{
attribute1: 'value1', // same as from the input
attribute2: 'value2', // same as from the input
assets: [
{assetAttribute1: 'value1', // etc.} // input asset array index 0
]
},
{
attribute1: 'value1', // same as from the input
attribute2: 'value2', // same as from the input
assets: [
{assetAttribute2: 'value2', // etc.} // // input asset array index 1
]
},
]
码:
KStream<String, AClass> inputs = //...
KStream<String, AClass> output = inputs.map((key, aclass) -> {
return aclass.getAssets().stream().map(asset -> {
AClass transform = new AClass();
transform = aclass.clone();
transform.setAssets(Arrays.asList(asset));
return new KeyValue<String, AClass>(key, miaTransitAsset);
});
});
如您所见,这是行不通的。但是我现在仍然停留在如何使用Java Streams来实现这一目标上。您可以忽略kafka流,因为它基本相同。
谢谢你的帮助!
只用一个流就可以做到这一点,但是为了便于阅读,让mi分开了:
为简单起见,我为自己创建了一个类(希望可以从JSON描述中正确地得到它):
class Input {
String attribute1;
String attribute2;
List<Map<String, String>> assets;
public Input(String attribute1, String attribute2, List<Map<String, String>> assets) {
this.attribute1 = attribute1;
this.attribute2 = attribute2;
this.assets = assets;
}
}
然后进行一些愚蠢的初始化,以处理一些数据:
List<Map<String, String>> assets = new ArrayList<>();
Map<String, String> attributeMap1 = new HashMap<>();
Map<String, String> attributeMap2 = new HashMap<>();
attributeMap1.put("assetAttribute1", "value1");
attributeMap2.put("assetAttribute2", "value2");
assets.add(attributeMap1);
assets.add(attributeMap2);
Input input = new Input("value1", "value2", assets);
List<Input> inputs = Arrays.asList(input);
然后是lambda:
首先,您必须获取要提取的所有属性(将在其上创建新对象的资产列表):
List<Map<String, String>> extractedAssets = inputs
.stream()
.map(e -> e.assets)
.flatMap(Collection::stream)
.collect(Collectors.toList());
然后,对于这些资产中的每一个,您都需要一份以前输入内容的副本,但“资产”列表内容有所不同。因此最好的方法是为每个以前的extractAsset创建一个新对象:
List<Input> collect = extractedAssets.stream()
.map(e -> new Input(
input.attribute1,
input.attribute2,
Collections.singletonList(e)))
.collect(Collectors.toList());
这应该工作:)
或一个流:
List<Input> collect1 = inputs.
stream()
.map(e -> e.assets)
.flatMap(Collection::stream)
.map(e -> new Input(
inputs.get(0).attribute1,
inputs.get(0).attribute2,
Collections.singletonList(e)))
.collect(Collectors.toList());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句