Builders in HttpClient, Stream.Builder and more
40 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)ShopLite's code grew messy, and objects with too many settings are one cause. The JDK solves it with builders and static factories you already use; learn the two shapes and any API reads easily.
StringBuilder: a mutable builder for strings
A builder is an object that collects the settings of another object through chained steps and creates the finished object with one final call, such as build() or toString().
A receipt is made of many lines. A StringBuilder collects the pieces one append at a time and hands over one finished String at the end.
Example 1 · StringBuilder as a builder
import java.util.List;
public class ReceiptBuilderDemo { record Line(String item, int qty, int price) { }
public static void main(String[] args) { List<Line> lines = List.of(new Line("Notebook", 3, 60), new Line("Pen set", 1, 150));
StringBuilder receipt = new StringBuilder(); receipt.append("ShopLite receipt\n"); int total = 0; for (Line l : lines) { int amount = l.qty() * l.price(); receipt.append(l.item()).append(" x").append(l.qty()) .append(" = Rs. ").append(amount).append('\n'); total += amount; } receipt.append("Total: Rs. ").append(total);
String text = receipt.toString(); // the "build" step System.out.println(text);
StringBuilder sb = new StringBuilder("UPI"); System.out.println("append returns the same builder: " + (sb.append("-123") == sb)); System.out.println("Builder still usable: " + sb.insert(0, "Paid by ")); }}ShopLite receipt Notebook x3 = Rs. 180 Pen set x1 = Rs. 150 Total: Rs. 330 append returns the same builder: true Builder still usable: Paid by UPI-123
What this code does
- The receipt is assembled in many
appendsteps and finished withtoString(), the builder's "build" step. sb.append("-123") == sbistrue: each step returns the same builder, which makes chaining possible. The builder still works aftertoString().
Each append returns the same StringBuilder, which is why calls can be chained. The builder stays usable after toString(), so you can keep adding or take another snapshot.
StringBuilder is looser: it is a reusable, mutable buffer. Both share the idea of "many steps, then one finished product".HttpClient and HttpRequest builders
A fluent API is an API whose methods return an object so that calls can be chained into one readable line, such as .header(...).timeout(...).GET().
A request needs a URI, headers, a timeout and maybe a body, and most are optional. Chain only the settings you need and finish with build().
Example 2 · HttpClient and HttpRequest builders
import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.time.Duration;
public class HttpBuildersDemo { public static void main(String[] args) { // Building objects only: nothing is sent over the network here HttpClient client = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(5)) .followRedirects(HttpClient.Redirect.NORMAL) .build(); System.out.println("Client timeout: " + client.connectTimeout().orElseThrow()); System.out.println("Client redirects: " + client.followRedirects());
HttpRequest list = HttpRequest.newBuilder() .uri(URI.create("https://shoplite.example/api/v1/products?page=0")) .header("Accept", "application/json") .timeout(Duration.ofSeconds(10)) .GET() .build(); System.out.println(list.method() + " " + list.uri()); System.out.println("Accept: " + list.headers().firstValue("Accept").orElse("-"));
HttpRequest create = HttpRequest.newBuilder(URI.create("https://shoplite.example/api/v1/orders")) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString("{\"productId\":7,\"quantity\":2}")) .build(); System.out.println(create.method() + " " + create.uri().getPath() + " body bytes: " + create.bodyPublisher().orElseThrow().contentLength());
try { HttpRequest.newBuilder().GET().build(); } catch (IllegalStateException e) { System.out.println("build() without a URI: " + e.getMessage()); } }}Client timeout: PT5S Client redirects: NORMAL GET https://shoplite.example/api/v1/products?page=0 Accept: application/json POST /api/v1/orders body bytes: 28 build() without a URI: uri is null
What this code does
- Only the settings that matter are chained; the rest keep their defaults. Building the objects does not touch the network.
build()checks the required URI and throwsIllegalStateException: uri is nullwhen it is missing, just like the Builder pattern's validation step.
build() checks the required parts: a request without a URI throws IllegalStateException. The built HttpClient and HttpRequest (Java 11 and later) are immutable, so one client is safely shared by the whole app.
The usual steps:
HttpClient.newBuilder():connectTimeout,followRedirects,version,executor, thenbuild().HttpRequest.newBuilder(uri):header,timeout,GET()/POST(body)/PUT(body)/DELETE(), thenbuild().HttpRequest.Builder.copy()starts a new builder with the same settings, handy for a retry with one extra header.
Predict the output
Predict what build() does
Pick what each piece of code does.
Round 1 of 2
What happens when this runs?
Stream.builder(): a stream step by step
Sometimes the items come from separate checks, not one ready list. Stream.builder() lets you add each one inside an if, then call build() to get the stream.
Example 3 · Stream.builder with optional items
import java.util.stream.Collectors;import java.util.stream.Stream;
public class StreamBuilderDemo { public static void main(String[] args) { boolean giftWrap = true; boolean express = false;
Stream.Builder<String> charges = Stream.builder(); charges.add("Items").add("GST"); if (giftWrap) { charges.add("Gift wrap"); } if (express) { charges.add("Express delivery"); }
Stream<String> stream = charges.build(); System.out.println(stream.collect(Collectors.joining(", ")));
try { charges.add("Late fee"); } catch (IllegalStateException e) { System.out.println("add after build: IllegalStateException"); } }}Items, GST, Gift wrap add after build: IllegalStateException
What this code does
- Items are added one by one, with
ifdeciding which charges appear.build()turns them into a normal stream. - Adding after
build()throwsIllegalStateException: aStream.Builderis used once.
A Stream.Builder is used once: after build(), calling add again throws IllegalStateException, because the stream already owns the items.
Find the bug
Find the failing line
Click the line that throws IllegalStateException.
Which line throws?
Round 1 of 2Factory methods in the JDK: List.of, Path.of, Executors
A static factory method is a static method that returns a new or ready-made object, used instead of new, such as List.of(...) or Integer.valueOf(...).
List.of, Path.of and Executors.newFixedThreadPool all return an object without new. The example shows what each one does that a constructor cannot.
Example 4 · Static factories in the JDK
import java.nio.file.Path;import java.util.List;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;
public class JdkFactoriesDemo { public static void main(String[] args) throws Exception { List<String> sizes = List.of("S", "M", "L"); try { sizes.add("XL"); } catch (UnsupportedOperationException e) { System.out.println("List.of gives a fixed list: add is not allowed"); }
Path report = Path.of("reports", "2026", "october.csv"); System.out.println("Path.of: " + report.getNameCount() + " parts, file " + report.getFileName());
Integer a = Integer.valueOf(100); Integer b = Integer.valueOf(100); System.out.println("Integer.valueOf(100) twice, same object: " + (a == b));
ExecutorService pool = Executors.newFixedThreadPool(2); Future<Integer> gst = pool.submit(() -> 1000 * 18 / 100); System.out.println("Executors pool computed GST: " + gst.get()); pool.shutdown(); }}List.of gives a fixed list: add is not allowed Path.of: 3 parts, file october.csv Integer.valueOf(100) twice, same object: true Executors pool computed GST: 180
What this code does
List.ofreturns a fixed list;Path.ofbuilds a path from parts. You never see or name the concrete class.Integer.valueOf(100)returns the same cached object twice, which a constructor can never do.Executors.newFixedThreadPool(2)hides a long constructor.
The JDK uses a few name styles: of (List.of, Path.of, LocalDate.of), valueOf (Integer.valueOf), newX (Executors.newFixedThreadPool) and getInstance in older APIs.
Factories can do what constructors cannot. List.of returns an unmodifiable list whose class you never name. Integer.valueOf returns a cached object for values from -128 to 127. Executors.newFixedThreadPool hides the many ThreadPoolExecutor constructor arguments behind one good default.
Predict the output
Predict the factory result
Pick what the program prints.
Round 1 of 2
What does this print?
Spotting builder vs factory from an API's shape
Read the shape of the call, not the name. A builder has chained steps and a finishing call; a factory is one static call that takes everything at once.
Example 5 · Same objects, builder shape and factory shape
import java.time.LocalDate;import java.time.format.DateTimeFormatter;import java.time.format.DateTimeFormatterBuilder;import java.util.Locale;
public class SpotTheShapeDemo { public static void main(String[] args) { // Builder shape: new X.Builder(), several setters, build() Locale india = new Locale.Builder().setLanguage("en").setRegion("IN").build(); // Factory shape: one static call with everything at once Locale sameIndia = Locale.forLanguageTag("en-IN"); System.out.println(india.toLanguageTag() + " equals " + sameIndia.toLanguageTag() + ": " + india.equals(sameIndia));
DateTimeFormatter longDate = new DateTimeFormatterBuilder() .appendPattern("dd MMM yyyy") .appendLiteral(" (") .appendPattern("EEEE") .appendLiteral(")") .toFormatter(Locale.ENGLISH); DateTimeFormatter shortDate = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate delivery = LocalDate.of(2026, 10, 16); System.out.println("Builder: " + delivery.format(longDate)); System.out.println("Factory: " + delivery.format(shortDate)); }}en-IN equals en-IN: true Builder: 16 Oct 2026 (Friday) Factory: 16/10/2026
What this code does
new Locale.Builder()...build()andLocale.forLanguageTaggive equal locales: the builder for many options, the factory for the quick case.DateTimeFormatterBuilderends withtoFormatter, notbuild. Look for the chained calls and a finishing call, not a fixed name.
Many JDK types offer both: new Locale.Builder()...build() and Locale.forLanguageTag("en-IN") make equal objects. The builder is there for the many-options case, the factory for the common simple case.
Clues to look for:
- Builder: chained calls, optional settings, a final
build-like call (build(),toFormatter(),toString()). - Factory: one static method named
of,from,valueOf,newXorgetInstance. - Mixed:
HttpRequest.newBuilder(uri)is a factory that returns a builder.
Predict the output
Builder or factory?
Read the shape of each call.
Round 1 of 3
Which shape is this call?
Next step
Check your understanding
12 quick questions