Sub List or partition list according to index in java 8 using Stream API

Question is like this, Create a method Stream<String> streamSection(Stream<String> stream, int m, int n) which extracts a substream from the input stream stream consisting of all elements from position m to position n , inclusive; you must use only Stream operations to do this. You can assume 0 <= m <= n .

Solution:
public class Section {

    public static Stream<String> streamSection(Stream<String> stream, int m, int n) {

        return stream.skip(m).limit(n - m + 1);
        

    }

    public static void main(String[] args) {

        System.out.println(streamSection(nextStream(), 0, 3).collect(Collectors.joining(", ")));
        System.out.println(streamSection(nextStream(), 2, 5).collect(Collectors.joining(", ")));
        System.out.println(streamSection(nextStream(), 7, 8).collect(Collectors.joining(", ")));
    }

    //support method for the main method -- for testing
    private static Stream<String> nextStream() {
        return Arrays.asList("aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii").stream();

    }

}

Output:
aaa, bbb, ccc
eee, fff, ggg, hhh, iii
ccc, ddd, eee, fff, ggg, hhh


Happy Coding !!!

0 comments:

Post a Comment