Java8, convert for lambda condition loop

Java 8.

Converting a forEach loop to a lambda expression is understood, at least for me. On the other hand, condition-based for loop conversion is not.

If possible, my question would be: how can you convert the following for a loop into a lambda expression

List<Field> fields = new LinkedList<>();
        for (Class<?> c = this.getClass(); c != null; c = c.getSuperclass())
            Collections.addAll(fields, c.getDeclaredFields());

Thank you very much in advance,

~ Ben.

+4
source share
2 answers

Well, there is a way, but he needs takeWhileit to be in jdk-9.

I am doing a mapping here to get the field names. You need to add a method @SuppressWarnings("null").

System.out.println(Stream.iterate(this.getClass(), (Class<?> x) -> x.getSuperclass())
            .takeWhile(x -> x != null)
            .flatMap(c -> Arrays.stream(c.getDeclaredFields()))
            .map(c -> c.getName())
            .collect(Collectors.toList()));

jdk-9 Stream.iterate, Iterator seed, hasNext, next, .

StreamEx btw:

 StreamEx.of(Stream.iterate(this.getClass(), (Class<?> x) -> x.getSuperclass()))
            .takeWhile(x -> x != null)
            .flatMap(c -> Arrays.stream(c.getDeclaredFields()))
            .map(c -> c.getName())
            .collect(Collectors.toList());

:

 Stream.iterate(this.getClass(), c -> c != null, (Class<?> c) -> c.getSuperclass())
            .flatMap(c -> Arrays.stream(c.getDeclaredFields()))
            .map(c -> c.getName())
            .collect(Collectors.toList())
+5

, . . FunctionalInterface/Lambda.

0

Source: https://habr.com/ru/post/1671124/


All Articles