java 字段摘要,如何使用Java流对字段进行分组并创建摘要

public class Call {

private String status;

private String callName;

}

I have a list of calls and i have to create a summary, like this:

public class CallSummary {

private String callName;

private List items;

}

public class itemSummary {

private String status;

private Integer percentage;

}

My goal is show a percentage of calls with some status

like :

INBOUND_CALL : {

FAILED = 30%

SUCCESS = 70%

}

how can i do it using java 8 stream and Collectors ?

解决方案

The idea behind the grouping would be to nest is in such a way that you have a call name and then status based count lookup available. I would also suggest using an enumeration for the status

enum CallStatus {

FAILED, SUCCESS

}

and adapting it in other classes as

class Call {

private CallStatus status;

private String callName;

}

Then you can implement a nested grouping and start off with an intermediate result such as:

List sampleCalls = List.of(new Call(CallStatus.SUCCESS,"naman"),new Call(CallStatus.FAILED,"naman"),

new Call(CallStatus.SUCCESS,"diego"), new Call(CallStatus.FAILED,"diego"), new Call(CallStatus.SUCCESS,"diego"));

Map> groupedMap = sampleCalls.stream()

.collect(Collectors.groupingBy(Call::getCallName,

Collectors.groupingBy(Call::getStatus, Collectors.counting())));

which would give you an output of

{diego={FAILED=1, SUCCESS=2}, naman={FAILED=1, SUCCESS=1}}

and you can further evaluate the percentages as well. (though representing them in Integer might lose precision depending on how you evaluate them further.)

To solve it further, you can keep another Map for the name-based count lookup as:

Map nameBasedCount = calls.stream()

.collect(Collectors.groupingBy(Call::getCallName, Collectors.counting()));

and further, compute summaries of type CallSummary in a List as :

List summaries = groupedMap.entrySet().stream()

.map(entry -> new CallSummary(entry.getKey(), entry.getValue().entrySet()

.stream()

.map(en -> new ItemSummary(en.getKey(), percentage(en.getValue(),

nameBasedCount.get(entry.getKey()))))

.collect(Collectors.toList()))

).collect(Collectors.toList());

where percentage count be implemented by you using the signature int percentage(long val, long total) aligned with the datatype chosen in ItemSummary as well.

Sample result:

[

CallSummary(callName=diego, items=[ItemSummary(status=FAILED, percentage=33), ItemSummary(status=SUCCESS, percentage=66)]),

CallSummary(callName=naman, items=[ItemSummary(status=FAILED, percentage=50), ItemSummary(status=SUCCESS, percentage=50)])

]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值