Erlang Port Swap Feature for Java 8 with Lambda Expressions and Threads

Is it possible to write the following Erlang code only with Java 8 Java expressions and Java 8 threads? This is from List Comprehensions 3.3 Permutations

perms([]) -> [[]]; perms(L) -> [[H|T] || H <- L, T <- perms(L--[H])]. 
+5
source share
1 answer

Using triple op to replace pattern matching, flatMap to replace multiple generators and static methods to implement | and - operations:

 import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class Example { public static <E> List<E> pipe(E head, List<E> tail) { List<E> newList = new ArrayList<>(tail); newList.add(0, head); return newList; } public static <E> List<E> subtract(List<E> list, E e) { List<E> newList = new ArrayList<>(list); newList.remove(e); return newList; } public static <E> List<List<E>> perms(List<E> l) { return l.isEmpty() ? Collections.singletonList(Collections.emptyList()) : l.stream().<List<E>> flatMap(h -> perms(subtract(l, h)).stream().map(t -> pipe(h, t))) .collect(toList()); } public static void main(String[] args) { List<String> list = Arrays.asList(new String[] { "b", "u", "g" }); System.out.println(perms(list)); } } 

Explicit type specification in .<List<E>> flatMap( needed only because of inadequate type inference from the Java compiler.

+7
source

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


All Articles