Yield Return In Java

后端 未结 10 1244
春和景丽
春和景丽 2020-12-13 23:13

I\'ve created a linked list in java using generics, and now I want to be able to iterate over all the elements in the list. In C# I would use yield return insid

10条回答
  •  心在旅途
    2020-12-13 23:43

    It's been ages since this question was posted, and I'm quite unsure about writing an answer to such an old question, but another way of achieving this has occurred to me and I want to present it here in case it helps anyone searching for this, given the fact that this SO thread was one of the very first hits in Google.

    The code shown below has been compiled in my head. There's absolutely no guarantee it's correct, but the idea behind it is.

    Use callbacks

    Yes, I know, it is not the same as a yield return. But I don't think OP wanted specifically a replacement that could be (with the appropriate amount of sugar) dropped into a for (var x : ). My approach instead does something more akin to C#'s linq (or Java's stream()), not the yielded return.

    @FunctionalInterface
    public interface Looper {
        void each(T item);
    }
    
    
    
    public interface Loopable {
        void forEach(Looper looper);
    }
    

    Then you would implement Loopable in your code, creating this pseudo-iterator. Which is really not, it's just making use of @FunctionalInterfaces, which is Java's way of doing callbacks (sorta)

    public class WhatEvs implements Loopable {
        // ...
        @Override
        public void forEach(Looper looper) {
            while(your_condition) {
                WhatEvs nextItem = getNextItem();
                looper.each(nextItem);
            }
        }
    }
    

提交回复
热议问题