lambda - Should I use the java Stream.map Function together with an switch statement? -


I want to move one stream of objects into different objects on one type basis. For example:

  stream & lt; Animals & gt; Animal = erase Stream (arrays.Sistlist (new animal ("A"), new animal ("B")); Stream result = animals Map (Animals) - & gt; {Switch (animal .gettype ()) {case "A": new bird (animal) returned; Case "B": new lion (animal) returned; Case "C": New tiger (animal) returned; Case "D": New fish (animal) returned; }}  

Is this a functional-programming "anti-pattern"?

Can I get the above methodology differently with programming?

(Note: I also do not like that every time I add a new type, I have to update all my switch statements)

@ TMB is correct, it is not related to functional programming.

As you said:

Every time I add a new type, I have to update all my switch statements

Software institutions (classes, modules, functions etc.) should be open for expansion, but have been closed for revision

You make this animal factory Which can 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 category AnimalFactory {Private Final Map & lt; String, function & lt; Animals, Object & gt; & Gt; DelegateFactories = New Hashmap & lt; String, function & lt; Animals, Object & gt; & Gt; (); Public Animals (String Type, Function & Animal; Object & gt; Factory) with Physical; {delegateFactories.put (Type, Factory); This return; } Creating Public ObjectsAnimal (Animal Animals) {Return Representative Factories.get (animal.getType ()). Applicable (animal); }}  

You can use it easily:

  public static zero main (string [] args) {stream & lt; Animals & gt; Animals = Aries.Sistrict (new animal ("A"), new animal ("B")). Stream (); Animal husbandry animal = factory = new animalfisher (); Animalfighter Vitamin ("A", Bird :: New); Animal factory Vitamin ("B", Lion :: New); Cattle store Vitamin ("C", Tiger :: New); Animal factory Vitamin ("D", Fish :: New); Stream result = animals.map (AnimalFinor :: CreateAngel); }  

Comments

Popular posts from this blog

sqlite3 - UPDATE a table from the SELECT of another one -

c# - Showing a SelectedItem's Property -

javascript - Render HTML after each iteration in loop -