What will this code output? public class StreamApi { @Data @AllArgsConstructor public static class Client { private String name; private String city; } public static Map<String, Long> countBy(Stream<Client> clients, Function<Client, String> clientParameterGetter) { return clients.collect(Collectors.groupingBy(clientParameterGetter, TreeMap::new, Collectors.counting())); } public static void main(String[] args) { List<Client> clients = List.of( new Client("Ivanov", "Moscow"), new Client("Mikhailov", "Saint Petersburg"), new Client("Sergeev", "Saint Petersburg"), new Client("Ivanov", null), new Client("Sergeev", null) ); long count = clients.stream() .peek(client -> { if (client.getCity() == null) { client.setCity("Moscow"); } }) .count(); Predicate<Client> clientPredicate = client -> client.getCity() != null; Stream<Client> validClients = clients.stream().filter(clientPredicate); System.out.println(count); System.out.println(countBy(validClients, Client::getName)); System.out.println(countBy(validClients, Client::getCity)); } }
sobes.tech AI
Answer from AI
The code will output the following:
-
The variable
countis the number of elements in the listclients. Since there are 5 clients in the list,countwill be 5. -
The method
countBygroups clients by a specified parameter and counts the number of clients in each group. -
It is important that before counting,
peekis called in the stream, which replacesnullin thecityfield with "Moscow". This modifies the objects in the original list, as the objects are mutable. -
Next, a stream
validClientsis created, which filters clients with a non-emptycity. Afterpeek, all clients havecitynotnull(for the two where it wasnull, it is now "Moscow"), so the filter will pass all 5 clients. -
The first call to
countBy(validClients, Client::getName)groups clients by name:
- "Ivanov" — 2 clients
- "Mikhaylov" — 1 client
- "Sergeev" — 2 clients
- The second call to
countBy(validClients, Client::getCity)groups by city:
- "Moscow" — 3 clients (Ivanov with
nullreplaced by "Moscow", Sergeev withnullreplaced by "Moscow", and Ivanov originally with "Moscow") - "Saint Petersburg" — 2 clients
Final output:
5
{Ivanov=2, Mikhaylov=1, Sergeev=2}
{Moscow=3, Saint Petersburg=2}
The key point is that peek modifies objects in the original list, which affects subsequent filtering and grouping.