Sobes.tech
Senior

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:

  1. The variable count is the number of elements in the list clients. Since there are 5 clients in the list, count will be 5.

  2. The method countBy groups clients by a specified parameter and counts the number of clients in each group.

  3. It is important that before counting, peek is called in the stream, which replaces null in the city field with "Moscow". This modifies the objects in the original list, as the objects are mutable.

  4. Next, a stream validClients is created, which filters clients with a non-empty city. After peek, all clients have city not null (for the two where it was null, it is now "Moscow"), so the filter will pass all 5 clients.

  5. The first call to countBy(validClients, Client::getName) groups clients by name:

  • "Ivanov" — 2 clients
  • "Mikhaylov" — 1 client
  • "Sergeev" — 2 clients
  1. The second call to countBy(validClients, Client::getCity) groups by city:
  • "Moscow" — 3 clients (Ivanov with null replaced by "Moscow", Sergeev with null replaced 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.

What will this code output? public class StreamApi {… - sobes.tech