Generator functions equivalent in Java

后端 未结 7 873
后悔当初
后悔当初 2020-12-01 03:50

I would like to implement an Iterator in Java that behaves somewhat like the following generator function in Python:

def iterator(array):
   for         


        
7条回答
  •  猫巷女王i
    2020-12-01 03:59

    Indeed Java has no yield, but you can now use Java 8 streams. IMO it's really a complicated iterator since it's backed by an array, not a function. Given it's a loop in a loop in a loop can be expressed as a Stream using filter (to skip the nulls) and flatMap to stream the inner collection. It's also about the size of the Python code. I've converted it to an iterator to use at your leisure and printed to demonstrate, but if all you were doing was printing, you could end the stream sequence with forEach(System.out::println) instead of iterator().

    public class ArrayIterate
    {
        public static void main(String args[])
        {
            Integer[][][] a = new Integer[][][] { { { 1, 2, null, 3 },
                                                    null,
                                                    { 4 }
                                                  },
                                                  null,
                                                  { { 5 } } };
    
            Iterator iterator = Arrays.stream(a)
                                              .filter(ax -> ax != null)
                                              .flatMap(ax -> Arrays.stream(ax)
                                                   .filter(ay -> ay != null)
                                                   .flatMap(ay -> Arrays.stream(ay)
                                                   .filter(az -> az != null)))
                                              .iterator();
    
            while (iterator.hasNext())
            {
                System.out.println(iterator.next());
            }
        }
    }
    
    
    

    I'm writing about implementation of generators as part of my blog on Java 8 Functional Programming and Lambda Expressions at http://thecannycoder.wordpress.com/ which might give you some more ideas for converting Python generator functions into Java equivalents.

    提交回复
    热议问题