Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
polymorphic mapper
//'main' method must be in a class 'Rextester'. //Compiler version 1.8.0_111 import java.util.function.*; import java.util.stream.*; import java.util.*; import java.lang.*; class Rextester { public static void main(String args[]) { Function<A, Stream<P>> mapper = PolymorphicMapper.<A, Stream<P>> builder() .caseClass(B.class, b -> IntStream.range(0, b.value).mapToObj(num -> new P(String.format("%02d", num)))) .caseClass(C.class, c -> Stream.of(new P(String.format("%s %s", c.s1, c.s2)))) .build(); List<A> inputs = Arrays.asList(new B(1), new C("hello", "world"), new B(10), new C("bonjour", "toi")); String result = inputs.stream() .map(mapper) .flatMap(Function.identity()) .map(P::toString) .collect(Collectors.joining(", ")); System.out.println(result); } static abstract class A { } static class B extends A { public int value; B(int value) { this.value = value; } } static class C extends A { public String s1; public String s2; C(String s1, String s2) { this.s1 = s1; this.s2 = s2; } } static class P { public String id; P(String id) { this.id = id; } @Override public String toString() { return String.format("P(id=%s)", id); } } static class PolymorphicMapper<T, R> { static <T, R> PolymorphicMapper<T, R> builder() { return new PolymorphicMapper<T, R>(); } private Map<Class<?>, Function<Object, R>> mappers = new LinkedHashMap<>(); private PolymorphicMapper() { } @SuppressWarnings("unchecked") public <K extends T> PolymorphicMapper<T, R> caseClass(Class<K> targetClass, Function<K, R> mapper) { mappers.put(targetClass, (Function<Object, R>) mapper); return this; } public Function<T, R> build() { return value -> { for (Map.Entry<Class<?>, Function<Object, R>> entry: mappers.entrySet()) { if (entry.getKey().isInstance(value)) { return entry.getValue().apply(value); } } throw new IllegalArgumentException("Could not find mapper for value: " + value); }; } } }
run
|
edit
|
history
|
help
0
pk2
hw1p1
Umang Khambhalikar
pow x^n
continue
Coding Numbers - Duplicate - HashSet
Convert ArrayList to array in java
String object comparision
Reverse a String
Display Page (Pagination)