Sobes.tech
Junior — Middle

Can you give an example of data transformation methods within the Stream API?

sobes.tech AI

Answer from AI

In the Stream API (for example, in Java), transformation methods allow creating new streams based on existing ones with modified elements. Examples of such methods:

  • map() — applies a function to each element and returns a stream of transformed elements.
  • filter() — filters elements based on a given condition.
  • flatMap() — transforms each element into a stream and merges all streams into one.
  • distinct() — removes duplicates.
  • sorted() — sorts the elements.

Example:

List<String> names = Arrays.asList("Anna", "Bob", "Charlie", "David");

List<String> filteredNames = names.stream()
    .filter(name -> name.startsWith("A"))  // keep names starting with 'A'
    .map(String::toUpperCase)               // convert to uppercase
    .collect(Collectors.toList());

System.out.println(filteredNames); // [ANNA]
Can you give an example of data transformation… - sobes.tech