如何将Java 8中的Stream流式代码转换为Java 7兼容实现?
Alright, let's break down how to swap that stream-based code for Java 7-compatible logic. The original line uses streams, lambdas, and method references—features that didn't exist in Java 7, so we'll replace them with traditional iteration that does exactly the same job.
What the Original Code Does
First, let's clarify the purpose of the line you need to update:
sourceCollection.stream().map(o -> convertValue(o, targetClass)).forEach(result::add);
This code loops through every element in sourceCollection, converts each element using convertValue(o, targetClass), then adds the converted result to the result ArrayList.
Java 7 Replacement
The cleanest Java 7 alternative is an enhanced for-loop (introduced in Java 5, fully supported in Java 7). Here's the direct drop-in replacement:
for (Object o : sourceCollection) { T convertedValue = convertValue(o, targetClass); result.add(convertedValue); }
If you prefer using an explicit iterator (functionally identical, just more verbose), you can also write it like this:
Iterator<?> iterator = sourceCollection.iterator(); while (iterator.hasNext()) { Object o = iterator.next(); T convertedValue = convertValue(o, targetClass); result.add(convertedValue); }
Full Modified Method
Here's your complete getValues method with the Java 7-compatible code:
public <T> List<T> getValues(CommandLineItem commandLineItemMod, Class<T> targetClass) { Object value = values.get(commandLineItemMod); ArrayList<T> result = new ArrayList<>(); if (value instanceof Collection) { Collection<?> sourceCollection = (Collection<?>) value; result.ensureCapacity(sourceCollection.size()); // Java 7 replacement for the stream pipeline for (Object o : sourceCollection) { T convertedValue = convertValue(o, targetClass); result.add(convertedValue); } } else if (value != null) { result.add(convertValue(value, targetClass)); } return result; }
Key Notes
- We kept the
result.ensureCapacity(sourceCollection.size())line because it's a smart performance choice (pre-allocates space for the list to avoid resizing, just like the original code intended). - The
convertValuemethod doesn't need any changes—since it's already being called elsewhere in the method, it's already Java 7-friendly.
内容的提问来源于stack exchange,提问作者Mohamed MAOUCHI

