Member-only story
Java Streams — Python List/Dict Comprehension But In Java
3 min readOct 30, 2021
If you clicked on this article, I’m guessing that you might be a Python main who needs to work with Java for whatever reason — be it for work or an existing project etc.
A Simple Sample Problem
Let’s say we have a list containing 3 string values:
The list in Python
list1 = ["apple", "orange", "pear"]
The ArrayList in Java
List<String> list1 = new ArrayList<>();
list1.add("apple");
list1.add("orange");
list1.add("pear");
Let’s say that we want to create another list containing the uppercase versions of the fruits inside ["APPLE", "ORANGE", "PEAR"]
In Python, this is how we might get this new list:
list2 = []
for fruit in list1:
list2.append(fruit.upper())print(list2) # ["APPLE", "ORANGE", "PEAR"]
This would be the equivalent in Java:
List<String> list2 = new ArrayList<>();for (String fruit: list1) {
list2.add(fruit.toUpperCase());
}System.out.println(list2);
If you think this method is long and unelegant, here’s a shorter way to do it: