简单的map-reduce的java例子

来源:互联网 发布:星星知我心主题曲原唱 编辑:程序博客网 时间:2024/05/17 09:10

需求是去除一个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()));