fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.util.stream.Collectors;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. List<String> listKeys = new ArrayList<>(List.of("A", "B", "C"));
  13.  
  14. Map<User, Long> mapUsers = new HashMap<>();
  15. mapUsers.put(new User("Annie", "A"), 23L);
  16. mapUsers.put(new User("Paul", "C"), 16L);
  17.  
  18. List<UserCount> listRes = listKeys.stream()
  19. .map(key -> {
  20. User user = mapUsers.keySet().stream().filter(u -> u.getKey().equals(key)).findFirst().orElse(null);
  21. return new UserCount(key, user != null ? mapUsers.get(user) : 0L);
  22. })
  23. .collect(Collectors.toList());
  24.  
  25. System.out.println(listRes);
  26. }
  27. }
  28.  
  29. class User {
  30. private String name, key;
  31.  
  32. public User(String name, String key) {
  33. this.name = name;
  34. this.key = key;
  35. }
  36.  
  37. public String getName() {
  38. return name;
  39. }
  40.  
  41. public String getKey() {
  42. return key;
  43. }
  44.  
  45. @Override
  46. public boolean equals(Object obj) {
  47. if (obj == this) return true;
  48. if (obj == null) return false;
  49. if (obj.getClass() != getClass()) return false;
  50. User other = (User) obj;
  51. return Objects.equals(name, other.getName()) && Objects.equals(key, other.getKey());
  52. }
  53.  
  54. @Override
  55. public int hashCode() {
  56. return Objects.hash(name, key);
  57. }
  58.  
  59. public String toString() {
  60. return String.format("%s - %s", name, key);
  61. }
  62. }
  63.  
  64. class UserCount {
  65. private String key;
  66. private long count;
  67.  
  68. public UserCount(String key, long count) {
  69. this.key = key;
  70. this.count = count;
  71. }
  72.  
  73. public String getKey() {
  74. return key;
  75. }
  76.  
  77. public long getCount() {
  78. return count;
  79. }
  80.  
  81. @Override
  82. public boolean equals(Object obj) {
  83. if (obj == this) return true;
  84. if (obj == null) return false;
  85. if (obj.getClass() != getClass()) return false;
  86. UserCount other = (UserCount) obj;
  87. return Objects.equals(key, other.getKey()) && Objects.equals(count, other.getCount());
  88. }
  89.  
  90. @Override
  91. public int hashCode() {
  92. return Objects.hash(key, count);
  93. }
  94.  
  95. public String toString() {
  96. return String.format("%s - %d", key, count);
  97. }
  98. }
Success #stdin #stdout 0.12s 48920KB
stdin
Standard input is empty
stdout
[A - 23, B - 0, C - 16]