I'm trying to change my way of thinking to be more functional. Here's the sample code which I'm trying to change to be more functional.
List<Integer> numbers = Arrays.asList(1, 2 ,3, 4, 5, 6);
ArrayList<Integer> multipledByTwo = new ArrayList<Integer>();
for(Integer number : numbers) {
multipledByTwo.add(number * 2);
}
As far as I understand about functional java, the simplest rule which is no shared state. Am I correct to understand that this code there's a shared state which is multipledByTwo. Here's my version of functional java.
class MultipleByTwoIteration {
public static List<Integer> map(List<Integer> numbers) {
ArrayList<Integer> multipledByTwo = new ArrayList<Integer>();
for(Integer number : numbers) {
multipledByTwo.add(multipleByTwo(number));
}
return multipledByTwo;
}
private static Integer multipleByTwo(Integer number) {
return number * 2;
}
}
So I could just do
List<Integer> numbers = Arrays.asList(1, 2 ,3, 4, 5, 6);
List<Integer> multipledByTwo = MultipleByTwoIteration.map(numbers);
Am I correct that this is more of a functional way thinking? How do I improve my code if it's not functional?
Thanks.
Lists.transformdoes just that. It's a Java way of map