Far*_*med 2 java declarative-programming java-stream groupingby
我用谷歌搜索了它,但我主要找到了按聚合字段分组或更改流响应的案例,但不是以下场景:
我有一个User带有字段category和marketingChannel.
我必须以声明式风格编写一个方法,该方法接受用户列表并基于category和基于marketingChannel单独(即 not groupingBy(... ,groupingBy(..)))计算用户
。
我无法在一个循环中完成。这是我必须达到的目标。
我编码了一些方法如下:
import java.util.*;
import java.util.stream.*;
public class Main
{
public static void main(String[] args) {
List<User> users = User.createDemoList();
imperative(users);
declerativeMultipleLoop(users);
declerativeMultipleColumn(users);
}
public static void imperative(List<User> users){
Map<String, Integer> categoryMap = new HashMap<>();
Map<String, Integer> channelMap = new HashMap<>();
for(User user : users){
Integer value = categoryMap.getOrDefault(user.getCategory(), 0);
categoryMap.put(user.getCategory(), value+1);
value = channelMap.getOrDefault(user.getMarketingChannel(), 0);
channelMap.put(user.getMarketingChannel(), value+1);
}
System.out.println("imperative");
System.out.println(categoryMap);
System.out.println(channelMap);
}
public static void declerativeMultipleLoop(List<User> users){
Map<String, Long> categoryMap = users.stream()
.collect(Collectors.groupingBy(
User::getCategory, Collectors.counting()));
Map<String, Long> channelMap = users.stream()
.collect(Collectors.groupingBy(
User::getMarketingChannel, Collectors.counting()));
System.out.println("declerativeMultipleLoop");
System.out.println(categoryMap);
System.out.println(channelMap);
}
public static void declerativeMultipleColumn(List<User> users){
Map<String, Map<String, Long>> map = users.stream()
.collect(Collectors.groupingBy(
User::getCategory,
Collectors.groupingBy(User::getMarketingChannel,
Collectors.counting())));
System.out.println("declerativeMultipleColumn");
System.out.println("groupingBy category and marketChannel");
System.out.println(map);
Map<String, Long> categoryMap = new HashMap<>();
Map<String, Long> channelMap = new HashMap<>();
for (Map.Entry<String, Map<String, Long>> entry: map.entrySet()) {
String category = entry.getKey();
Integer count = entry.getValue().size();
Long value = categoryMap.getOrDefault(category,0L);
categoryMap.put(category, value+count);
for (Map.Entry<String, Long> channelEntry : entry.getValue().entrySet()){
String channel = channelEntry.getKey();
Long channelCount = channelEntry.getValue();
Long channelValue = channelMap.getOrDefault(channel,0L);
channelMap.put(channel, channelValue+channelCount);
}
}
System.out.println("After Implerative Loop on above.");
System.out.println(categoryMap);
System.out.println(channelMap);
}
}
class User{
private String name;
private String category;
private String marketChannel;
public User(String name, String category, String marketChannel){
this.name = name;
this.category = category;
this.marketChannel = marketChannel;
}
public String getName(){
return this.name;
}
public String getCategory(){
return this.category;
}
public String getMarketingChannel(){
return this.marketChannel;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return Objects.equals(name, user.name) &&
Objects.equals(category, user.category) &&
Objects.equals(marketChannel, user.marketChannel);
}
@Override
public int hashCode() {
return Objects.hash(name, category, marketChannel);
}
public static List<User> createDemoList(){
return Arrays.asList(
new User("a", "student","google"),
new User("b", "student","bing"),
new User("c", "business","google"),
new User("d", "business", "direct")
);
}
Run Code Online (Sandbox Code Playgroud)
该方法
declerativeMultipleLoop是声明性的,但每个字段都有一个单独的循环。复杂度:O(noOfFields * 用户数)
问题出在
declerativeMultipleColumnMethod 中,因为我最终编写了命令式代码和多个循环。
我想以完全声明式且尽可能高效的方式编写上述方法。即复杂性:O(用户数)
示例输出:
命令式
{business=2, student=2}
{direct=1, google=2, bing=1}
declarativeMultipleLoop
{business=2, student=2}
{direct=1, google=2, bing=1}
declarativeMultipleColumn
groupingBy category and marketChannel
{business={direct=1, google=1}, student={google=1, bing=1}}
在上面的祈求循环之后。
{business=2, student=2}
{direct=1, google=2, bing=1}
如果我理解您的要求,那就是使用单个流操作,从而产生 2 个单独的地图。这将需要一个结构来保存地图和一个收集器来构建结构。类似于以下内容:
class Counts {
public final Map<String, Integer> categoryCounts = new HashMap<>();
public final Map<String, Integer> channelCounts = new HashMap<>();
public static Collector<User,Counts,Counts> countsCollector() {
return Collector.of(Counts::new, Counts::accept, Counts::combine, CONCURRENT, UNORDERED);
}
private Counts() { }
private void accept(User user) {
categoryCounts.merge(user.getCategory(), 1, Integer::sum);
channelCounts.merge(user.getChannel(), 1, Integer::sum);
}
private Counts combine(Counts other) {
other.categoryCounts.forEach((c, v) -> categoryCounts.merge(c, v, Integer::sum));
other.channelCounts.forEach((c, v) -> channelCounts.merge(c, v, Integer::sum));
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
然后可以将其用作收集器:
Counts counts = users.stream().collect(Counts.countsCollector());
counts.categoryCounts.get("student")...
Run Code Online (Sandbox Code Playgroud)
(仅限意见:在这种情况下,命令式和声明式之间的区别非常随意。对我来说,定义流操作感觉非常程序化(与 Haskell 中的等价物相反))。
| 归档时间: |
|
| 查看次数: |
69 次 |
| 最近记录: |