fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6. import java.util.function.Function;
  7.  
  8. /* Name of the class has to be "Main" only if the class is public. */
  9. class Ideone
  10. {
  11. public static void main(String[] args) {
  12.  
  13. HashMap<SomeClass, Integer> myMap = new HashMap<SomeClass, Integer>() {{
  14. put(new SomeClass(2, 26), 10);
  15. put(new SomeClass(8, 25), 5);
  16. put(new SomeClass(5, 24), 5);
  17. }};
  18.  
  19. float resultOne = average(myMap, SomeClass::getMyInt);
  20. float resultTwo = average(myMap, SomeClass::getAge);
  21. System.out.println(resultOne);
  22. System.out.println(resultTwo);
  23. }
  24.  
  25. public static float average(HashMap<SomeClass, Integer> myMap, Function<SomeClass, Integer> getterFunc) {
  26.  
  27. float totalAmount = 0;
  28. float buffer = 0;
  29. for (SomeClass aClass : myMap.keySet()) {
  30. totalAmount += myMap.get(aClass);
  31. buffer += getterFunc.apply(aClass) * myMap.get(aClass);
  32. }
  33. return buffer / (totalAmount * myMap.size());
  34. }
  35.  
  36. public static class SomeClass {
  37.  
  38. private final int myInt;
  39.  
  40. private final int age;
  41.  
  42. public SomeClass(int myInt, int age) {
  43.  
  44. this.myInt = myInt;
  45. this.age = age;
  46. }
  47.  
  48. public int getAge() {
  49.  
  50. return age;
  51. }
  52.  
  53. public int getMyInt() {
  54.  
  55. return myInt;
  56. }
  57. }
  58. }
Success #stdin #stdout 0.08s 33792KB
stdin
Standard input is empty
stdout
1.4166666
8.416667