From Streams to Comprehensions
Lesson 20 of 48 in Coddy's Python for Java Developers course.
Build a list with an expression and an optional filter: [expression for value in source if condition]. This resembles a Java stream filter/map pipeline, but a list comprehension eagerly creates a list. sorted returns a new list and accepts a key function such as len; values.sort mutates an existing list and returns None. Java List.sort likewise mutates its list and returns void. Python sorting is stable, so equal keys keep their input order. The examples select pear and plum in that order; printed list quoting differs between the languages.
Java excerpt: inside main
var words = java.util.List.of("pear", "fig", "plum");
var result = words.stream().filter(w -> w.length() >= 4)
.sorted(java.util.Comparator.comparingInt(String::length)).toList();
System.out.println(result);Python
words = ["pear", "fig", "plum"]
result = sorted([w for w in words if len(w) >= 4], key=len)
print(result)Watch the difference
Pass key=len, not key=len(words). A key function computes one comparable key per item; it is not a Java two-argument Comparator. Avoid transforming the input when the API promises preservation.
Practice
Apply this comparison in the task below. Editable files: main.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Challenge
BeginnerRead lowercase words from one line and a nonnegative minimum length from the next. Retain words meeting the minimum, including duplicates. Order them by increasing length and preserve input order for equal lengths. Print one word per line, or none if empty. Python sorted with a key replaces a Java stream sort using a length comparator.
Editable files: main.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.
Keep the supplied input scaffold. Output only the requested results, with a newline after each line and no prompts.
Try it yourself
# Starts the program in main.py. Edit main.py to solve the challenge.
from runpy import run_module
run_module("main", run_name="__main__")
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler