I/O streams A common example is std::istream and std::ostream (the input and output stream classes) in
C++, where for example returns the left object, allowing chaining. a
Functional programming Functional programming is another example of the usage of method chaining, involving higher-order functions. In
object-oriented programming, higher-order functions and manipulation of collections can be represented through methods that are chained together. One such example in
Java uses the built-in methods of java.util.stream.Stream: import java.util.Arrays; import java.util.List; import java.util.streams.Collectors; List numbers = Arrays.asList(10, 25, 30, 45, 60, 75, 90); List result = numbers.stream() // .stream() returns java.util.stream.Stream .filter(n -> n > 30) .map(n -> n * 2) .sorted() .collect(Collectors.toList()); Note that in Java, filter(), map(), and sorted() return a new shallow copy of the preceding list. However, to operate on the list in-place, the sort() method can be used.
Language Integrated Query (or LINQ) for
C# makes extensive usage of method chaining. using System; using System.Collections; // using method chaining: IEnumerble results = SomeCollection .Where(c => c.SomeProperty new {c.SomeProperty, c.OtherProperty}); results.ForEach(x => { Console.WriteLine(x.ToString()); }); // using LINQ keywords: IEnumerable results = from c in SomeCollection where c.SomeProperty
C++20 introduces operator| (the piping operator) and allows LINQ-style chaining operations with the std::ranges namespaces. std::views contains several classes which are invoked through operator(). import std; using std::vector; using std::ranges::to; using std::views::filter; using std::views::transform; vector numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // Pipeline: filter even numbers, double them, and then sum the result vector result = numbers | filter([](int n) -> bool { return n % 2 == 0; }) | transform([](int n) -> int { return n * 2; }) | to();
Design patterns The Builder pattern relies on constructing an object through method calls rather than immediately in its constructor. For example, java.lang.StringBuilder makes use method chaining to build a StringBuilder. StringBuilder sb = new StringBuilder(); String result = sb.append("Hello, ") .append("world!") .insert(0, "Greeting: ") .replace(10, 18, "beautiful ") .toString(); The Fluent interface pattern relies entirely on method chaining to implement method cascading. In C++, similar method chaining to Java and C# can be accomplished by having the methods return (for example, for a class StringBuilder, .append() and .replace() could have type StringBuilder& and return *this). However, in C++ it is important to be conscious of potential
object slicing if the returned reference is to a parent class, while other languages such as Java, C#, and
Rust are not subject to this problem. ==See also==