[英]How to do Groupby , Sum, Avg ,Min, Max on java collections?
I have been trying to build a functionality which will enable me filter data in Java collections. 我一直在尝试构建一个使我能够过滤Java集合中的数据的功能。 The end goal is to have somethings as follow.
最终目标是要有如下内容。
SomeBuilder(Collections)
.groupby("Key")
.filter("Key","Value")
.sum()
.getResult() ;
The functionality mostly resembles to sql world but not fully. 该功能大部分类似于sql world,但不完全相同。 My problem is how to filter collections like
List<HashMap<String,Object>
? 我的问题是如何过滤类似于
List<HashMap<String,Object>
集合?
How can I apply groupby logic on such collections ? 如何在此类集合上应用分组逻辑?
A snippet of code showing filtering of such collection will help a lot. 展示过滤此类集合的代码片段将大有帮助。 If Guava can do this please give an example.
如果番石榴可以做到这一点,请举一个例子。
Edit:- I have added an answer for this question but please suggest better ways of doing it. 编辑:-我已经为这个问题添加了答案,但是请提出更好的解决方法。 Hope this help others.
希望这对别人有帮助。 For doing Sum ,Avg ,Count will update as I go ahead with my project.
对于Sum,Avg,Count将随着我的项目的进行而更新。
Ok This is to answer my own question and which may help others. 好的,这是回答我自己的问题,可能会对他人有所帮助。 I will be using the builder pattern to get the effect of method chaining.
我将使用构建器模式来获得方法链接的效果。 For filtering of
用于过滤
List<HashMap<String,Object>>
, I used Guava, here is an example of what I tried to do. ,我用了番石榴,这是我尝试做的一个例子。 Not the best way but a starter.
不是最好的方法,而是入门。
private static Collection<HashMap<String, Object>> filter(
List<HashMap<String, Object>> resMap, final String key,
final Object value) {
Predicate<Map<String, Object>> keyValueMatch = new Predicate<Map<String, Object>>() {
public boolean apply(Map<String, Object> stringStringMap) {
return value.equals( stringStringMap.get(key));
}
};
Collection<HashMap<String, Object>> transformedList = Collections2.filter(resMap, keyValueMatch);
return transformedList;
}
The usage will be as follow. 用法如下。
Collection<HashMap<String, Object>> transformedList = filter(input,"Dep","GlobalWarming");
Hope this help. 希望对您有所帮助。 Any better suggestions are welcome.
欢迎任何更好的建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.