-
-
Notifications
You must be signed in to change notification settings - Fork 549
Expand file tree
/
Copy pathCrazyStreams.java
More file actions
272 lines (244 loc) · 10.1 KB
/
CrazyStreams.java
File metadata and controls
272 lines (244 loc) · 10.1 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package com.bobocode.fp;
import com.bobocode.fp.exception.EntityNotFoundException;
import com.bobocode.model.Account;
import com.bobocode.model.Sex;
import com.bobocode.util.ExerciseNotCompletedException;
import lombok.AllArgsConstructor;
import java.math.BigDecimal;
import java.time.Month;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.reducing;
import static java.util.stream.Collectors.toSet;
/**
* {@link CrazyStreams} is an exercise class. Each method represent some operation with a collection of accounts that
* should be implemented using Stream API. Every method that is not implemented yet throws
* {@link ExerciseNotCompletedException}.
* <p>
* TODO: remove exception throwing and implement each method using Stream API
* <p><p>
* <strong>TODO: to get the most out of your learning, <a href="https://www.bobocode.com">visit our website</a></strong>
* <p>
*
* @author Taras Boychuk
*/
@AllArgsConstructor
public class CrazyStreams {
private Collection<Account> accounts;
/**
* Returns {@link Optional} that contains an {@link Account} with the max value of balance
*
* @return account with max balance wrapped with optional
*/
public Optional<Account> findRichestPerson() {
return accounts.stream()
.sorted(Comparator.comparing(Account::getBalance).reversed())
.findFirst();
}
/**
* Returns a {@link List} of {@link Account} that have a birthday month equal to provided.
*
* @param birthdayMonth a month of birth
* @return a list of accounts
*/
public List<Account> findAccountsByBirthdayMonth(Month birthdayMonth) {
return accounts.stream()
.filter(a -> a.getBirthday().getMonth() == birthdayMonth)
.collect(Collectors.toList());
}
/**
* Returns a map that separates all accounts into two lists - male and female. Map has two keys {@code true} indicates
* male list, and {@code false} indicates female list.
*
* @return a map where key is true or false, and value is list of male, and female accounts
*/
public Map<Boolean, List<Account>> partitionMaleAccounts() {
return accounts.stream()
.collect(Collectors.groupingBy(a -> a.getSex().equals(Sex.MALE),
Collectors.toList()));
}
/**
* Returns a {@link Map} that stores accounts grouped by its email domain. A map key is {@link String} which is an
* email domain like "gmail.com". And the value is a {@link List} of {@link Account} objects with a specific email domain.
*
* @return a map where key is an email domain and value is a list of all account with such email
*/
public Map<String, List<Account>> groupAccountsByEmailDomain() {
return accounts.stream()
.collect(Collectors.groupingBy(a -> a.getEmail().split("@")[1],
Collectors.toList()));
}
/**
* Returns a number of letters in all first and last names.
*
* @return total number of letters of first and last names of all accounts
*/
public int getNumOfLettersInFirstAndLastNames() {
return accounts.stream()
.map(a -> a.getFirstName().toCharArray().length
+ a.getLastName().toCharArray().length)
.mapToInt(Integer::valueOf)
.sum();
}
/**
* Returns a total balance of all accounts.
*
* @return total balance of all accounts
*/
public BigDecimal calculateTotalBalance() {
return BigDecimal.valueOf(accounts.stream()
.map(Account::getBalance)
.mapToInt(BigDecimal::intValue)
.sum());
}
/**
* Returns a {@link List} of {@link Account} objects sorted by first and last names.
*
* @return list of accounts sorted by first and last names
*/
public List<Account> sortByFirstAndLastNames() {
return accounts.stream()
.sorted(Comparator.comparing(Account::getFirstName)
.thenComparing(Account::getLastName))
.collect(Collectors.toList());
}
/**
* Checks if there is at least one account with provided email domain.
*
* @param emailDomain
* @return true if there is an account that has an email with provided domain
*/
public boolean containsAccountWithEmailDomain(String emailDomain) {
return accounts.stream()
.map(a -> a.getEmail().split("@")[1])
.anyMatch(e -> e.equals(emailDomain));
}
/**
* Returns account balance by its email. Throws {@link EntityNotFoundException} with message
* "Cannot find Account by email={email}" if account is not found.
*
* @param email account email
* @return account balance
*/
public BigDecimal getBalanceByEmail(String email) {
return accounts.stream()
.filter(a -> a.getEmail().equals(email))
.map(Account::getBalance)
.findFirst()
.orElseThrow(() -> new EntityNotFoundException("Cannot find Account by email=" + email));
}
/**
* Collects all existing accounts into a {@link Map} where a key is account id, and the value is {@link Account} instance
*
* @return map of accounts by its ids
*/
public Map<Long, Account> collectAccountsById() {
return accounts.stream()
.collect(Collectors.toMap(
Account::getId,
a -> a
));
}
/**
* Filters accounts by the year when an account was created. Collects account balances by its emails into a {@link Map}.
* The key is {@link Account#email} and the value is {@link Account#balance}
*
* @param year the year of account creation
* @return map of account by its ids the were created in a particular year
*/
public Map<String, BigDecimal> collectBalancesByEmailForAccountsCreatedOn(int year) {
return accounts.stream()
.filter(a -> a.getCreationDate().getYear() == year)
.collect(Collectors.toMap(
Account::getEmail,
Account::getBalance
));
}
/**
* Returns a {@link Map} where key is {@link Account#lastName} and values is a {@link Set} that contains first names
* of all accounts with a specific last name.
*
* @return a map where key is a last name and value is a set of first names
*/
public Map<String, Set<String>> groupFirstNamesByLastNames() {
return accounts.stream()
.collect(Collectors.groupingBy(
Account::getLastName,
mapping(Account::getFirstName, toSet())
));
}
/**
* Returns a {@link Map} where key is a birthday month, and value is a {@link String} that stores comma and space
* -separated first names (e.g. "Polly, Dylan, Clark"), of all accounts that have the same birthday month.
*
* @return a map where a key is a birthday month and value is comma-separated first names
*/
public Map<Month, String> groupCommaSeparatedFirstNamesByBirthdayMonth() {
return accounts.stream()
.collect(Collectors.groupingBy(
a -> a.getBirthday().getMonth(),
mapping(Account::getFirstName, joining(", "))
));
}
/**
* Returns a {@link Map} where key is a {@link Month} of {@link Account#creationDate}, and value is total balance
* of all accounts that have the same value creation month.
*
* @return a map where key is a creation month and value is total balance of all accounts created in that month
*/
public Map<Month, BigDecimal> groupTotalBalanceByCreationMonth() {
return accounts.stream()
.collect(Collectors.groupingBy(
a -> a.getCreationDate().getMonth(),
reducing(BigDecimal.ZERO,Account::getBalance, BigDecimal::add)
));
}
/**
* Returns a {@link Map} where key is a letter {@link Character}, and value is a number of its occurrences in
* {@link Account#firstName}.
*
* @return a map where key is a letter and value is its count in all first names
*/
public Map<Character, Long> getCharacterFrequencyInFirstNames() {
return accounts.stream()
.map(Account::getFirstName)
.flatMapToInt(String::chars)
.mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(
c -> c,
counting()
));
}
/**
* Returns a {@link Map} where key is a letter {@link Character}, and value is a number of its occurrences ignoring
* case, in all {@link Account#firstName} and {@link Account#lastName} that are equal or longer than nameLengthBound.
* Inside the map, all letters should be stored in lower case.
*
* @return a map where key is a letter and value is its count ignoring case in all first and last names
*/
public Map<Character, Long> getCharacterFrequencyIgnoreCaseInFirstAndLastNames(int nameLengthBound) {
Function<Account, String> function = account -> {
String result = "";
if (account.getFirstName().length() >= nameLengthBound) {
result += account.getFirstName();
}
if (account.getLastName().length() >= nameLengthBound) {
result += account.getLastName();
}
return result.toLowerCase();
};
return accounts.stream()
.map(function)
.flatMapToInt(String::chars)
.mapToObj(c -> (char) c)
.collect(groupingBy(
c -> c,
counting()
));
}
}