Avoid using global variables in Java 8 stream reduce methods

I'm trying to use Java 8 to rewrite the implementation of Moore's voting algorithm to find the major elements in the array

The Java 7 implementation will look like this:

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];
}

The way I can think of is to use stream reduce to get the final result

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;
}

However, this method has compilation errors, and it also breaks the function purists. I have encountered this situation many times. What is the best way to deal with global variables in lambda expressions

Solution

As I told you in my comments, mutable objects cannot be used in lambda expressions But in your case, if you really want to apply the same algorithm, it will be difficult

This is the same as you want. If you don't find the majority, it returns - 1

public static int findCandidate(int ... nums) {
    Map<Integer,List<Integer>> map =
    Arrays.stream(nums)
          .@R_501_2419@ed()
          .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;
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>