How to fetch only first two stackFrames from StackFrameStream?

Viewed 109

I have a list of StackFrames by using walk method on StackFrameStream. But I need to find only first 3 stackFrames.

I have StackFrameStream by

List<StackFrame> stackFrameList =
                StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE).walk(stackFrameStream -> stackFrameStream.collect(Collectors.toList()));

System.out.println("All frames : \n" + stackFrameList.toString());
for (StackFrame stackFrame : stackFrameList) {
      System.out.println("stackFrame.getDeclaringClass()=>" + stackFrame.getDeclaringClass().toString());
      System.out.println("stackFrame.getLineNumber=>" + stackFrame.getLineNumber());
      System.out.println("stackFrame.getMethodName=>" + stackFrame.getMethodName());
      System.out.println();
}

I dont want to use stackFrameStream.collect(Collectors.toList()) and fetch whole list of stackFrames,

I just want first 3 elements

2 Answers

use limit to truncate:

 StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE)
        .walk(stackFrameStream -> stackFrameStream.limit(3).collect(Collectors.toList()));

You can also use IntStream to get the limited objects or objects at particular indexes.

static IntStream range(int startInclusive, int endExclusive)

Returns a sequential ordered IntStream from startInclusive (inclusive) to endInclusive (inclusive) by an incremental step of 1.

List< StackFrame > result = IntStream.range(0, 2).mapToObj(i-> stackFrameStream.get(i)).collect(Collectors.toList());
Related