【发布时间】:2018-03-28 17:48:51
【问题描述】:
这是我在Group, Sum byType then get diff using Java streams 上一个问题的延续。
按照建议,我应该作为单独的主题发布,而不是更新原始主题。
因此,通过我之前的一组问题,我已经实现了这一点,现在继续进行。
背景:
我有以下数据集
Sample(SampleId=1, SampleTypeId=1, SampleQuantity=5, SampleType=ADD),
Sample(SampleId=2, SampleTypeId=1, SampleQuantity=15, SampleType=ADD),
Sample(SampleId=3, SampleTypeId=1, SampleQuantity=25, SampleType=ADD),
Sample(SampleId=4, SampleTypeId=1, SampleQuantity=5, SampleType=SUBTRACT),
Sample(SampleId=5, SampleTypeId=1, SampleQuantity=25, SampleType=SUBTRACT)
Sample(SampleId=6, SampleTypeId=2, SampleQuantity=10, SampleType=ADD),
Sample(SampleId=7, SampleTypeId=2, SampleQuantity=20, SampleType=ADD),
Sample(SampleId=8, SampleTypeId=2, SampleQuantity=30, SampleType=ADD),
Sample(SampleId=9, SampleTypeId=2, SampleQuantity=15, SampleType=SUBTRACT),
Sample(SampleId=10, SampleTypeId=2, SampleQuantity=35, SampleType=SUBTRACT)
我目前正在使用这个:
sampleList.stream()
.collect(Collectors.groupingBy(Sample::getTypeId,
Collectors.summingInt(
sample -> SampleType.ADD.equalsIgnoreCase(sample.getSampleType())
? sample.getSampleQuantity() :
-sample.getSampleQuantity()
)));
还有这个
sampleList.stream()
.collect(Collectors.groupingBy(Sample::getSampleTypeId,
Collectors.collectingAndThen(
Collectors.groupingBy(Sample::getSampleType,
Collectors.summingInt(Sample::getSampleQuantity)),
map -> map.getOrDefault(SampleType.ADD, 0)
- map.getOrDefault(SampleType.SUBTRACT, 0))));
作为获得所需输出以在Map<Long, Integer> 中分组的公认答案:
{1=15, 2=10}
有了这个,我想知道是否可以将其扩展为更多内容。
首先,我怎样才能让它返回为Map<String, Integer> 而不是原来的Map<Long, Integer>。基本上,对于 SampleTypeId; 1 表示 HELLO,2 表示 WORLD。
所以我需要一个.map(或者可能是其他函数)通过调用一个函数比如convertType(sampleTypeId)来将数据从1转换为HELLO,从2转换为WORLD。所以预期的输出将是{"HELLO"=15, "WORLD"=10}。是对的吗?我应该如何编辑当前建议的解决方案?
最后,我想知道是否也可以将其返回到 Object 而不是 Map。所以假设我有一个对象; SummaryResult with (String) name and (int) result。所以它返回一个List<SummaryResult> 而不是原来的Map<Long, Integer>。我如何使用.map(或其他)功能来做到这一点?还是有其他方法可以做到这一点?预期的输出应该是这样的。
SummaryResult(name="hello", result=15),
SummaryResult(name="world", result=10),
非常感谢@M 之前给出的步骤中的解释。普罗霍罗夫。
更新:
更新后
sampleList.stream()
.collect(Collectors.groupingBy(sample -> convertType(sample.getSampleTypeId()),
Collectors.collectingAndThen(
Collectors.groupingBy(Sample::getSampleType,
Collectors.summingInt(Sample::getSampleQuantity)),
map -> map.getOrDefault(SampleType.ADD, 0)
- map.getOrDefault(SampleType.SUBTRACT, 0))));
private String convertType(int id) {
return (id == 1) ? "HELLO" : "WORLD";
}
【问题讨论】:
-
每个问题都应该是完整的。虽然链接可以作为附加资源很好,但它不能仅作为理解您的问题所需信息的来源。
-
@Pshemo 指出,我已经用一些背景信息更新了这个问题。谢谢。
标签: java java-8 java-stream collectors