加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

避免在Java 8 stream reduce方法中使用全局变量

发布时间:2020-12-15 04:48:12 所属栏目:Java 来源:网络整理
导读:我正在尝试使用 Java 8重写 Moore’s Voting Algorithm的实现来查找数组中的Majority元素. Java 7实现将是这样的: public int findCandidate(int[] nums) { int maj_index = 0,count = 1; for(int i=1; inums.length;i++){ if(count==0){ count++; maj_inde
我正在尝试使用 Java 8重写 Moore’s Voting Algorithm的实现来查找数组中的Majority元素.

Java 7实现将是这样的:

public int findCandidate(int[] nums) {

    int maj_index = 0,count = 1;
    for(int i=1; i<nums.length;i++){
        if(count==0){
            count++;
            maj_index=i;
        }else if(nums[maj_index]==nums[i]){
            count++;
        } else {
            count--;
        }
    }
    return nums[maj_index];
}

我能想到的方法是使用stream reduce来获得最终结果

public int findCandidate(int[] nums) {
    int count = 1;
    Arrays
            .asList(nums)
            .stream()
            .reduce(0,(result,cur) -> {
                if (count == 0) {
                    result = cur;
                    count++;
                } else if (result == cur){
                    count++;
                } else {
                    count --;
                }
            });
    return result;
}

但是这个方法有编译错误,而且它也打破了函数纯粹主义者,我多次遇到这种情况,那么处理lambda表达式中的全局变量的最佳方法是什么.

解决方法

就像我在评论中告诉你的那样,在lambda表达式中使用可变对象是不行的.但在你的情况下,如果你真的想要应用相同的算法,那将很困难.

这是一个与你想要的相同的,如果没有找到多数,它返回-1

public static int findCandidate(int ... nums) {
    Map<Integer,List<Integer>> map =
    Arrays.stream(nums)
          .boxed()
          .collect(Collectors.groupingBy(x -> x));
    int value = 
          map
          .entrySet().stream()
          .max((e1,e2) -> Integer.compare(e1.getValue().size(),e2.getValue().size()))
          .map(e -> e.getKey())
          .get();
    int result = map.get(value).size();
    return result > nums.length / 2 ? value : -1;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读