简单的map-reduce的java例子

需求是去除一个key为long型,value为元素为integer的list的map的value的值。


public class test1 {
  public static void main(String[] args) {
    Map<Long, Integer> map = Maps.newHashMapWithExpectedSize(5);
    map.put(1l, Objects.hashCode(Lists.newArrayList(1, 2, 3)));
    map.put(2l, Objects.hashCode(Lists.newArrayList(2, 3, 4)));
    map.put(3l, Objects.hashCode(Lists.newArrayList(1, 2, 3)));
    map.put(4l, Objects.hashCode(Lists.newArrayList(1, 2, 5)));
    map.forEach((k, v) -> System.out.println(k + " - " + v));
    System.out.println("---------------------------------");
    System.out.println(
        map.entrySet().stream().collect(groupingBy(Map.Entry::getValue))
            .values().stream()
            .map(v -> v.get(0).getKey()).collect(Collectors.toList())
    );
    System.out.println("---------------------------------");
    System.out.println(
        map.entrySet().stream().collect(groupingBy(Map.Entry::getValue)).values().stream()
            .map(e -> e.stream().reduce((e1, e2) -> e1).get().getKey()).collect(Collectors.toList()));
  }
}

这里使用java8的编码风格:
1.首先初始化一个key为long型,value为list型的map
2.代码是分为两种处理方式,一种map操作之后,输出去除重复的key值,第二种是map操作后,进行reduce操作后输出去处重复的key值。
3.首先取得map的entryset的流,然后接入一个收集器,收集器里面进行groupingBy操作,groupingBy是java8的方法,以map的value分组,把map重新输出为里一个map,新map的key为旧map的不重复value,新map的value是和当前新map的key值对应旧map的key的list,有点绕。这样新map的每个元素的value就是不重复的值的key,对应代码中就是(1,2,3)的1l和3l。然后我们取每个新map的value的任意一个值即可。
4.取得新map的values,做成流,取每个元素的第一个值,收集成list,就是去除重复的旧map的key值。
5.通过reduce方式,在取得新map的values后做成流在map操作里,调用reduce操作,查看reduce源码可见,传入的参数是一个二元操作符,如下打开的java8的lambda表达式。二元操作传入两个同样类型的变量,输出一个同样类型的返回值。这里的二元操作就是传入e1,e2,然后返回e1,很简单的逻辑。当然这里的逻辑也可以返回e2,因为是任意选一个元素返回即可。

System.out.println(
        map.entrySet().stream().collect(groupingBy(Map.Entry::getValue)).values().stream()
            .map(e -> {
              return e.stream().reduce(new BinaryOperator<Map.Entry<Long, Integer>>() {
                @Override
                public Map.Entry<Long, Integer> apply(Map.Entry<Long, Integer> e1, Map.Entry<Long, Integer> e2) {
                  return e1;
                }
              }).get().getKey();
            }).collect(Collectors.toList()));
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值