0

I have the following method in Java 8 and I'm working in project using java 7:

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());
        sourceCollection.stream().map(o -> convertValue(o, targetClass)).forEach(result::add);
    } else if (value != null) {
        result.add(convertValue(value, targetClass));
    }

    return result;
}

my question is how I can transfer the following line from java 8 to java 7 :

 sourceCollection.stream().map(o -> convertValue(o, targetClass)).forEach(result::add);

thank you for your help

2 Answers 2

2

The line

sourceCollection.stream().
                .map(o -> convertValue(o, targetClass))
                .forEach(result::add);

can be rewritten as:

for (Object o: sourceCollection) {
    result.add(convertValue(o, targetClass));
}

which (IMO) is a clearer way to write the code in the first place.


Having said that, public (free) support for Java 7 ended in 2015, and premium (paid) support ended in Jul7 2019. (See https://www.oracle.com/java/technologies/java-se-support-roadmap.html). So the application you are working on is on borrowed time. I would have thought it would be more sensible to port the application to a newer Java version (or phase it out entirely) rather than expending valuable developer effort on backporting Java 8 code to it.

Sign up to request clarification or add additional context in comments.

Comments

1

Java 7 doesn't support Stream API. You have to use a for loop:

 for(Object source : sourceCollection){
     result.add(convertValue(source, targetClass));
 }

1 Comment

thanks for the help

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.