I should put Java stream Is the map function used with the switch statement?
•
Java
I want to stream objects to different objects according to type
Stream<Animal> animals = Arrays.stream(Arrays.asList(new Animal("A"),new Animal("B")));
Stream result = animals.map(animal) ->{
switch (animal.getType()) {
case "A" : return new Bird(animal);
case "B" : return new LION(animal);
case "C" : return new Tiger(animal);
case "D" : return new FISH(animal);
}
}
Is this a functional programming "anti pattern"?
Can I implement the above differences through functional programming?
(Note: I also don't like that I need to update all switch statements every time I add a new type)
Solution
@Timb is correct in its answer This has nothing to do with functional programming
As you said:
Your "factory lambda" breaks the open / closed principle:
You can create animal factories that follow this principle:
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Stream;
public class AnimalFactory {
private final Map<String,Function<Animal,Object>> delegateFactories
= new HashMap<String,Object>>();
public AnimalFactory withFactory(String type,Object> factory) {
delegateFactories.put(type,factory);
return this;
}
public Object createAnimal(Animal animal) {
return delegateFactories.get(animal.getType()).apply(animal);
}
}
You can easily use it before taking advantage of Java 8 feature:
public static void main(String[] args) {
Stream<Animal> animals = Arrays.asList(new Animal("A"),new Animal("B")).stream();
AnimalFactory animalFactory = new AnimalFactory();
animalFactory.withFactory("A",Bird::new);
animalFactory.withFactory("B",Lion::new);
animalFactory.withFactory("C",Tiger::new);
animalFactory.withFactory("D",Fish::new);
Stream result = animals.map(animalFactory::createAnimal);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
