Change elements with map
30 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)You have a list of employee objects but only need their names, or every price with tax added. You want to change each element, not remove any.
Why map exists
map turns every element into a new value using a Function, producing a stream of the results.
Data rarely arrives in the shape you need. You have marks but need grades. You have Student objects but the notice board needs names. You have prices without GST but the bill needs prices with GST.
Example 1 · Loop versus map: add grace marks
import java.util.ArrayList;import java.util.List;
public class GraceMarksDemo { public static void main(String[] args) { List<Integer> marks = List.of(35, 62, 88, 47);
List<Integer> loopResult = new ArrayList<>(); for (int m : marks) { loopResult.add(m + 5); } System.out.println("Loop: " + loopResult);
List<Integer> withGrace = marks.stream() .map(m -> m + 5) .toList(); System.out.println("Stream: " + withGrace); System.out.println("Source: " + marks);
List<String> names = List.of("asha", "ravi", "meena"); System.out.println(names.stream().map(String::toUpperCase).toList()); }}Loop: [40, 67, 93, 52] Stream: [40, 67, 93, 52] Source: [35, 62, 88, 47] [ASHA, RAVI, MEENA]
What this code does
- Four marks go in and four come out, each one 5 higher, in the same order.
mapnever drops or adds elements. - The source list is unchanged.
String::toUpperCaseis a method reference forn -> n.toUpperCase(). - Why: one pass in both.
mapshows at a glance that every element changes and none is dropped, which a loop makes you read to find out.
With a loop you write the frame again: an empty list, a loop, a calculation, add. map keeps the frame and asks only for the calculation: prices.stream().map(p -> p * 118 / 100). Like filter, it is an intermediate operation, so it runs only when a terminal operation such as toList() pulls the elements through. map never drops or adds elements. Five elements go in and five results come out, in the same order. Dropping is the job of filter.
How map works, one element at a time
Take the names "asha", "ravi", "meena" and the pipeline names.stream().map(n -> n.toUpperCase()).toList().
import java.util.*;
public class UpperNames { public static void main(String[] args) { List<String> names = List.of("asha", "ravi", "meena"); List<String> upper = names.stream().map(n -> n.toUpperCase()).toList(); System.out.println(upper); System.out.println(names); }}[ASHA, RAVI, MEENA] [asha, ravi, meena]
"asha"arrives. The function returns"ASHA", and"ASHA"moves on totoList()."ravi"arrives and becomes"RAVI"."meena"arrives and becomes"MEENA". The result is[ASHA, RAVI, MEENA].- The source list still holds the small-letter names.
mapbuilds new values; it does not edit the old ones.
map can change the element type
The function given to map is a Function<T, R>: it takes a T and returns an R, and R may be a different type. So map turns a Stream<T> into a Stream<R>.
Example 2 · Changing the type: Stream<Student> to Stream<String>
import java.util.List;import java.util.stream.Stream;
record Student(String name, int marks) {}
public class ChangeTypeDemo { public static void main(String[] args) { List<Student> students = List.of( new Student("Asha", 78), new Student("Ravi", 91), new Student("Meena", 66));
Stream<Student> studentStream = students.stream(); Stream<String> nameStream = studentStream.map(s -> s.name()); Stream<Integer> lengthStream = nameStream.map(n -> n.length()); System.out.println("Name lengths: " + lengthStream.toList());
List<String> labels = students.stream() .map(s -> s.name() + " (" + s.marks() + ")") .toList(); System.out.println("Labels: " + labels); }}Name lengths: [4, 4, 5] Labels: [Asha (78), Ravi (91), Meena (66)]
What this code does
- The typed variables show each step:
Stream<Student>becomesStream<String>, which becomesStream<Integer>. Eachmaphands its result type to the next step. - The second pipeline maps each student to a label String. Normally you chain the steps without the variables, as there.
Example 3 · Real-world use: marks to report rows
import java.util.List;
record Student(String name, int marks) {}
record ReportLine(String name, String grade) {}
public class ReportCardDemo { static String grade(int marks) { if (marks >= 90) return "A+"; if (marks >= 75) return "A"; if (marks >= 60) return "B"; if (marks >= 40) return "C"; return "F"; }
public static void main(String[] args) { List<Student> students = List.of( new Student("Asha", 78), new Student("Ravi", 91), new Student("Meena", 34), new Student("Kiran", 66));
List<ReportLine> report = students.stream() .map(s -> new ReportLine(s.name(), grade(s.marks()))) .toList();
for (ReportLine line : report) { System.out.println(line.name() + " : " + line.grade()); } }}Asha : A Ravi : A+ Meena : F Kiran : B
What this code does
mapcan build a new object from each element. Here everyStudentbecomes aReportLinewith only what the report needs.- The grading rule lives in its own method,
grade(int), so the lambda stays one short line.
students.stream() is a Stream<Student>. After .map(s -> s.name()) it is a Stream<String>. After .map(name -> name.length()) it is a Stream<Integer>. Each step works only with what the step before it produced. Once you map a Student to its name, the marks are gone for the rest of the pipeline. The same idea builds new objects: .map(s -> new ReportLine(s.name(), grade(s.marks()))) turns raw students into exactly the rows a report needs.
.map(Student::name) is the same as .map(s -> s.name()), and .map(String::toUpperCase) the same as .map(n -> n.toUpperCase()).Chaining map with filter in a readable order
Ask one question for each filter: does it test the original element or the new value? If it tests a field of the original, such as marks, filter before you map the marks away.
Example 4 · Mistake: filtering on a field after mapping it away
import java.util.List;
record Student(String name, int marks) {}
public class WrongOrderDemo { public static void main(String[] args) { List<Student> students = List.of(new Student("Asha", 78), new Student("Meena", 34)); List<String> passed = students.stream() .map(s -> s.name()) .filter(s -> s.marks() >= 40) .toList(); System.out.println(passed); }}WrongOrderDemo.java:10: error: cannot find symbol
.filter(s -> s.marks() >= 40)
^
symbol: method marks()
location: variable s of type String
1 errorWhat this code does
- After
.map(s -> s.name())the stream holds Strings, so thesin the filter is aString. AStringhas nomarks()method, and the compiler says so. - The fix is to filter while the elements are still students:
.filter(s -> s.marks() >= 40).map(s -> s.name()).
Example 5 · Filter before or after map, by what it tests
import java.util.List;
record Item(String name, int price) {}
public class GstBillDemo { public static void main(String[] args) { List<Item> cart = List.of( new Item("Headphones", 1500), new Item("Pen drive", 700), new Item("Mouse", 900), new Item("Keyboard", 1200));
List<String> cheapNames = cart.stream() .filter(i -> i.price() < 1000) .map(i -> i.name()) .toList(); System.out.println("Under Rs 1000: " + cheapNames);
List<Integer> bigBills = cart.stream() .map(i -> i.price() * 118 / 100) .filter(total -> total > 1000) .toList(); System.out.println("Bills above Rs 1000 with GST: " + bigBills); }}Under Rs 1000: [Pen drive, Mouse] Bills above Rs 1000 with GST: [1770, 1062, 1416]
What this code does
- The first filter tests the original price, so it comes before the
mapthat keeps only the name. - The second filter tests the price with 18% GST, a value that exists only after the
map. The Mouse is Rs 900 before GST and Rs 1062 after, so it passes.
If it tests the result, such as the price after GST, filter after the map that computes it.
Filtering first also saves work, because map then runs only on the elements you keep. A pipeline then reads top to bottom like a sentence: keep the students who passed, take their names, make them uppercase.
Fix the error
Fix the step order
Read the real compiler error, then pick the line that fixes it.
Print the names of students with 40 marks or more.
Error
MapFix.java:8: error: cannot find symbol
list.stream().map(Student::name).filter(s -> s.marks() >= 40).forEach(System.out::println);
symbol: method marks()
location: variable s of type StringTrap: map is not for printing
A side effect is anything a function does besides returning its value, such as printing, adding to a list or saving to a file. map should only compute a new value. Hiding a println inside it causes two problems.
Example 6 · Trap: printing inside map
import java.util.List;
public class MapSideEffectDemo { public static void main(String[] args) { List<String> names = List.of("Asha", "Ravi", "Meena");
System.out.println("With count():"); long n = names.stream() .map(s -> { System.out.println(" mapping " + s); return s.toUpperCase(); }) .count(); System.out.println("count = " + n);
System.out.println("Printing the right way:"); names.stream() .map(String::toUpperCase) .forEach(s -> System.out.println(" " + s)); }}With count(): count = 3 Printing the right way: ASHA RAVI MEENA
What this code does
- No "mapping" line is printed.
count()knows the list has 3 elements and thatmapcannot change that, so it skips the map completely (Java 9 and later). - Printing belongs in the terminal operation
forEach.maponly returns a new value.
First, nothing runs until a terminal operation pulls elements, so the print may happen later than you expect, or never. Second, since Java 9 count() may skip map completely when it can tell the size from the source, because mapping cannot change how many elements there are. Your prints simply vanish. To print each element, use the terminal operation forEach(System.out::println). To look at elements in the middle of a pipeline while debugging, the lesson on peek shows the right tool.
Next step
Check your understanding
12 quick questions