1

Getting compilation error "Can only iterate over an array or an instance of java.lang.Iterable" at for loop in reducer.

public void reduce(Text key, Iterator<IntWritable> values,
            OutputCollector<Text, IntWritable> Output, Reporter arg3)
            throws IOException {
        // TODO Auto-generated method stub

        int sum = 0;
         for (IntWritable val : values) {
           sum += val.get();

In above code, getting compilation error "Can only iterate over an array or an instance of java.lang.Iterable" at "for (IntWritable val : values)". How to use loop in the same?

Rama
  • 815
  • 2
  • 17
  • 37

2 Answers2

2

Either pass an Iterable<IntWritable> instead of Iterator<IntWritable> to the method, or use hasNext() and next() to iterate over the elements of the Iterator :

 while (values.hasNext()) {
    IntWritable val = values.next();
    ...
}
Eran
  • 387,369
  • 54
  • 702
  • 768
2

Try this.

    for (IntWritable val : (Iterable<IntWritable>)() -> values) {
        sum += val.get();
        ....

(Iterable<IntWritable>)() -> values is equivalent to

    new Iterable<IntWritable>() {

        @Override
        public Iterator<IntWritable> iterator() {
            return values;
        }

    };