package org.codefx.demo.java9.api.stack_walking;

import java.lang.StackWalker.StackFrame;
import java.util.Arrays;
import java.util.stream.Stream;

class StackWalking {

	public static void main(String[] args) {
		oldWay();
		newWay();
	}

	static void oldWay() {
		StackTraceElement[] stackTrace = createStackTrace();
		String line = oldWalk(stackTrace);
		System.out.println(line);
	}

	private static String oldWalk(StackTraceElement[] stackTrace) {
		return Arrays.stream(stackTrace)
				.peek(frame -> System.out.println(frame.getMethodName()))
				.filter(frame -> frame.getMethodName().contains("oldWay"))
				.findFirst()
				.map(frame -> "Line " + frame.getLineNumber())
				.orElse("Unknown line");
	}

	private static StackTraceElement[] createStackTrace() {
		try {
			throw new RuntimeException();
		} catch (RuntimeException ex) {
			return ex.getStackTrace();
		}
	}

	static void newWay() {
		one();
	}

	static void one() {
		two();
	}

	static void two() {
		three();
	}

	static void three() {
		String line = StackWalker.getInstance().walk(StackWalking::newWalk);
		System.out.println(line);
	}

	private static String newWalk(Stream<StackFrame> stackFrameStream) {
		return stackFrameStream
				.filter(frame -> frame.getMethodName().contains("one"))
				.findFirst()
				.map(frame -> "Line " + frame.getLineNumber())
				.orElse("Unknown line");
	}

}

@@ -293,22 +293,35 @@
 Trace = 
-create
+new Throwable().get
 StackTra
@@ -725,178 +725,8 @@
 %09%7D%0A%0A
-%09private static StackTraceElement%5B%5D createStackTrace() %7B%0A%09%09try %7B%0A%09%09%09throw new RuntimeException();%0A%09%09%7D catch (RuntimeException ex) %7B%0A%09%09%09return ex.getStackTrace();%0A%09%09%7D%0A%09%7D%0A%0A
 %09sta

Create StackTrace without throwing an exception