fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.util.stream.Collectors;
  5. import java.util.function.Function;
  6. import static java.util.stream.Collectors.toMap;
  7.  
  8.  
  9. enum A {
  10. A1, A2, A3;
  11. }
  12.  
  13.  
  14.  
  15. interface B {
  16. Set<A> getSetOfA();
  17. }
  18.  
  19. class B1 implements B {
  20. @Override
  21. public Set<A> getSetOfA() { return Collections.singleton(A.A1); }
  22. }
  23.  
  24. class B2 implements B {
  25. @Override
  26. public Set<A> getSetOfA() {
  27. return new HashSet<>(Arrays.asList(A.A2, A.A3));
  28.  
  29. }
  30. }
  31.  
  32.  
  33.  
  34. /* Name of the class has to be "Main" only if the class is public. */
  35. class Ideone
  36. {
  37. public static void main (String[] args) throws java.lang.Exception
  38. {
  39. Set<B> setOfB = new HashSet<>(Arrays.asList(new B1(), new B2()));
  40.  
  41. Map<A, B> map = Arrays.stream(A.values())
  42. .collect(toMap(Function.identity()
  43. , a -> setOfB.stream()
  44. .filter(b -> b.getSetOfA().contains(a))
  45. .findAny()
  46. .orElseThrow(() -> new UnsupportedOperationException(a + "not supported"))
  47. ));
  48.  
  49. System.out.println(map);
  50.  
  51. }
  52. }
Success #stdin #stdout 0.09s 34444KB
stdin
Standard input is empty
stdout
{A2=B2@30f39991, A3=B2@30f39991, A1=B1@a09ee92}