Using Streams and Method References to Write Self-Documenting Processes
suggest changeMethod references make excellent self-documenting code, and using method references with Stream
s makes complicated processes simple to read and understand. Consider the following code:
public interface Ordered {
default int getOrder(){
return 0;
}
}
public interface Valued<V extends Ordered> {
boolean hasPropertyTwo();
V getValue();
}
public interface Thing<V extends Ordered> {
boolean hasPropertyOne();
Valued<V> getValuedProperty();
}
public <V extends Ordered> List<V> myMethod(List<Thing<V>> things) {
List<V> results = new ArrayList<V>();
for (Thing<V> thing : things) {
if (thing.hasPropertyOne()) {
Valued<V> valued = thing.getValuedProperty();
if (valued != null && valued.hasPropertyTwo()){
V value = valued.getValue();
if (value != null){
results.add(value);
}
}
}
}
results.sort((a, b)->{
return Integer.compare(a.getOrder(), b.getOrder());
});
return results;
}
This last method rewritten using Stream
s and method references is much more legible and each step of the process is quickly and easily understood - it’s not just shorter, it also shows at a glance which interfaces and classes are responsible for the code in each step:
public <V extends Ordered> List<V> myMethod(List<Thing<V>> things) {
return things.stream()
.filter(Thing::hasPropertyOne)
.map(Thing::getValuedProperty)
.filter(Objects::nonNull)
.filter(Valued::hasPropertyTwo)
.map(Valued::getValue)
.filter(Objects::nonNull)
.sorted(Comparator.comparing(Ordered::getOrder))
.collect(Collectors.toList());
}
Found a mistake? Have a question or improvement idea?
Let me know.
Using Streams and Method References to Write Self-Documenting Processes
Table Of Contents
3 Streams
7 Generics
8 File I/O
9 Arrays
10 Interfaces
11 Maps
12 Strings
18 Console I/O
19 Singletons
22 Autoboxing
26 JAXB
28 Networking
29 Optional
30 Enums
32 Annotations
33 Audio
34 Data Class
40 Operators
41 Asserting
42 Scanner
44 Preferences
46 Constructors
47 ByteBuffer
49 JSON in Java
51 Recursion
52 Polymorphism
56 Java Agents
59 BigInteger
60 BigDecimal
63 ThreadLocal
64 Logging
69 JVM Flags
76 Lists
78 LocalTime
79 Sets
90 JAX-WS
97 XJC
99 Process
102 Fluent Interface
107 Modules
110 ServiceLoader
111 ClasssLoader
115 Applets
116 NIO Networking
117 New File I/O
118 Secure objects
122 SecurityManager
123 JNDI
124 super keyword
127 Atomic types
130 sun.misc.Unsafe
132 Java deployment
135 Runtime commands
136 NumberFormat
139 Unit Testing
140 JavaBean
141 Expressions
142 Literals
145 Packages
151 JMX
154 JShell
155 Benchmarks
160 Sockets
161 Java Sockets
164 List vs. set
165 2D graphics
166 Reflection
167 Deque interface
168 Enum Map
169 EnumSet class
172 Immutable class
173 String Tokenizer
176 Hashtable
178 SortedMap
179 WeakHashMap
180 LinkedHashMap
181 StringBuffer
183 C++ Comparison
185 Contributors