|
Задача на сумму транзакций по счету (stream collector)
|
|||
---|---|---|---|
#18+
Всем привет! Решаю задачки. И вот попалась такая на которой залип. Исходные данные. Есть два класса - Счет и Транзакция. (представлены ниже в спойлере) Есть список транзакций по счетам. Задача. Нужно просуммировать сумму транзакций по счетам. Условие оригинал. Almost like a SQL: the total sum of transactions by each account. You have two classes: Account: number: String, balance: Long Transaction: uuid: String, sum: Long, account: Account Both classes have getters for all fields with the corresponding names (getNumber(), getSum(), getAccount() and so on). Write a collector that calculates the total sum of transactions (long type, not integer) by each account (i.e. by account number). The collector will be applied to a stream of transactions. Important. You should write only the collector in any valid formats but without ; on the end. It will be passed as an argument to the collect() method of a stream as shown below. List<Transaction> transactions = ... Map<String, Long> totalSumOfTransByEachAccount = transactions.stream() .collect( ...your_collector_will_be_passed_here... ); Examples of the valid solution formats: Collectors.reducing(...) or reducing(...) Main c классами Код: java 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57.
С представленными данными результат должен быть такой: 1001 - 300 1002 - 500 Не силен в стримах. Понимаю, что reduce в данном случае вроде как не годится. А с Collectors.reducing не получается подружиться. Пробовал делать через Collectors.groupingBy(), но получал либо "element cannot be mapped to a null key" либо "NullPointerException". Как же достучаться до Account в Transaction, как это сделать правильно? ... |
|||
:
Нравится:
Не нравится:
|
|||
04.09.2018, 12:07 |
|
Задача на сумму транзакций по счету (stream collector)
|
|||
---|---|---|---|
#18+
Imperous.... Пробовал делать через Collectors.groupingBy(), но получал либо "element cannot be mapped to a null key" либо "NullPointerException". .... Код: java 1. 2. 3. 4. 5. 6.
А где инициализация this.account в конструкторе? Под отлатчиком посмотреть не судьба или подумать, от чего может быть "element cannot be mapped to a null key" либо "NullPointerException" ? ... |
|||
:
Нравится:
Не нравится:
|
|||
04.09.2018, 13:08 |
|
Задача на сумму транзакций по счету (stream collector)
|
|||
---|---|---|---|
#18+
Добрый день , Сложно понять что нужно поучить ? Задача по SQL а решение должно быть на java ? ИЗ того что понял groupingby и/или collectingandthen https://stackoverflow.com/questions/34997501/java-8-stream-groupingby-summing-an-attributevalue https://www.javabrahman.com/java-8/java-8-how-to-use-collectors-collectingandthen-method-with-examples/ или так? http://www.mkyong.com/java8/java-8-collectors-groupingby-and-mapping-example/ ... |
|||
:
Нравится:
Не нравится:
|
|||
04.09.2018, 13:39 |
|
Задача на сумму транзакций по счету (stream collector)
|
|||
---|---|---|---|
#18+
Leonid KudryavtsevImperous.... Пробовал делать через Collectors.groupingBy(), но получал либо "element cannot be mapped to a null key" либо "NullPointerException". .... Код: java 1. 2. 3. 4. 5. 6.
А где инициализация this.account в конструкторе? Под отлатчиком посмотреть не судьба или подумать, от чего может быть "element cannot be mapped to a null key" либо "NullPointerException" ? Спасибо! :) Да, не сложилось под отладчиком. В конструкторах и методах не сомневался. Решение приняло. ... |
|||
:
Нравится:
Не нравится:
|
|||
04.09.2018, 14:21 |
|
Задача на сумму транзакций по счету (stream collector)
|
|||
---|---|---|---|
#18+
Atum1Добрый день , Сложно понять что нужно поучить ? Задача по SQL а решение должно быть на java ? ИЗ того что понял groupingby и/или collectingandthen https://stackoverflow.com/questions/34997501/java-8-stream-groupingby-summing-an-attributevalue https://www.javabrahman.com/java-8/java-8-how-to-use-collectors-collectingandthen-method-with-examples/ или так? http://www.mkyong.com/java8/java-8-collectors-groupingby-and-mapping-example/ Сделал, через grouppingBy. Мне все время не давала покоя вот эта фраза из условия "Examples of the valid solution formats: Collectors.reducing(...) or reducing(...)". Точней я ее неправильно понял. ... |
|||
:
Нравится:
Не нравится:
|
|||
04.09.2018, 14:24 |
|
|
start [/forum/topic.php?fid=59&fpage=40&tid=2121804]: |
0ms |
get settings: |
11ms |
get forum list: |
15ms |
check forum access: |
4ms |
check topic access: |
4ms |
track hit: |
36ms |
get topic data: |
11ms |
get forum data: |
2ms |
get page messages: |
58ms |
get tp. blocked users: |
2ms |
others: | 312ms |
total: | 455ms |
0 / 0 |