一种方法是为你要进行分组的字段集创建一个对象。该类可以构建成提供良好助手方法的样子。
因此,使用以下方式完成原始类:
public final class TaxLine {
private String title;
private BigDecimal rate;
private BigDecimal price;
public TaxLine(String title, BigDecimal rate, BigDecimal price) {
this.title = title;
this.rate = rate;
this.price = price;
}
public String getTitle() {
return this.title;
}
public BigDecimal getRate() {
return this.rate;
}
public BigDecimal getPrice() {
return this.price;
}
@Override
public String toString() {
return "TaxLine = title:\"" + this.title + "\", rate:" + this.rate + ", price:" + this.price;
}
}
并且分组辅助类定义如下:
public final class TaxGroup {
private String title;
private BigDecimal rate;
public static TaxLine asLine(Entry<TaxGroup, BigDecimal> e) {
return new TaxLine(e.getKey().getTitle(), e.getKey().getRate(), e.getValue());
}
public TaxGroup(TaxLine taxLine) {
this.title = taxLine.getTitle();
this.rate = taxLine.getRate();
}
public String getTitle() {
return this.title;
}
public BigDecimal getRate() {
return this.rate;
}
@Override
public int hashCode() {
return this.title.hashCode() * 31 + this.rate.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == null || getClass() != obj.getClass())
return false;
TaxGroup that = (TaxGroup) obj;
return (this.title.equals(that.title) && this.rate.equals(that.rate));
}
}
将行项目合并的代码如下,分成多行以帮助查看其各个部分:
List<TaxLine> lines = Arrays.asList(
new TaxLine("New York Tax", new BigDecimal("0.20"), new BigDecimal("20.00")),
new TaxLine("New York Tax", new BigDecimal("0.20"), new BigDecimal("20.00")),
new TaxLine("County Tax" , new BigDecimal("0.10"), new BigDecimal("10.00"))
);
List<TaxLine> combined =
lines
.stream()
.collect(Collectors.groupingBy(TaxGroup::new,
Collectors.reducing(BigDecimal.ZERO,
TaxLine::getPrice,
BigDecimal::add)))
.entrySet()
.stream()
.map(TaxGroup::asLine)
.collect(Collectors.toList());
您可以打印输入/输出:
System.out.println("Input:");
lines.stream().forEach(System.out::println);
System.out.println("Combined:");
combined.stream().forEach(System.out::println);
要生成此内容:
Input:
TaxLine = title:"New York Tax", rate:0.20, price:20.00
TaxLine = title:"New York Tax", rate:0.20, price:20.00
TaxLine = title:"County Tax", rate:0.10, price:10.00
Combined:
TaxLine = title:"New York Tax", rate:0.20, price:40.00
TaxLine = title:"County Tax", rate:0.10, price:10.00