fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Util
  9. {
  10. public static Class mostDerived(Collection<?> objects) {
  11. Optional<List<Class<?>>> mostDerived =
  12. objects.stream()
  13. .map(Util::getHierarchy)
  14. .reduce((l1, l2) -> {
  15. l1.retainAll(l2);
  16. return l1;
  17. });
  18. return mostDerived.map(l -> l.get(0)).orElse(null);
  19. }
  20.  
  21. private static List<Class<?>> getHierarchy(Object l) {
  22. List<Class<?>> result = new ArrayList<>();
  23. for (Class<?> clz = l.getClass(); clz != null; clz = clz.getSuperclass()) {
  24. result.add(clz);
  25. }
  26. return result;
  27. }
  28.  
  29. public static void main(String[] args) {
  30. assertEquals(A.class, Util.mostDerived(Arrays.asList(new B(), new B(), new C(), new A(), new B())));
  31. assertEquals(B.class, Util.mostDerived(Arrays.asList(new C(), new B(), new C(), new C(), new B())));
  32. assertEquals(A.class, Util.mostDerived(Arrays.asList(new B(), new D(), new B())));
  33. }
  34.  
  35. private static void assertEquals(Class<?> aClass, Class mostDerived) {
  36. if (!aClass.equals(mostDerived)) {
  37. throw new RuntimeException();
  38. }
  39. }
  40. }
  41.  
  42.  
  43. class A {};
  44.  
  45. class B extends A {};
  46.  
  47. class C extends B {};
  48.  
  49. class D extends A {};
  50.  
Success #stdin #stdout 0.14s 2184192KB
stdin
Standard input is empty
stdout
Standard output is empty