Before conversion:
String[] strArray = {"Apple", "Mandarin orange", "banana"};
** After conversion: **
Fruit ringo = new Fruit("Apple");
Fruit mikan = new Fruit("Mandarin orange");
Fruit banana = new Fruit("banana");
Fruit[] fruitArray = {ringo, mikan, banana};
OS:Windows 10 Java:Oracle JDK 11 (It is interpreted that it can be used free of charge for applications such as development and testing.)
String[] strArray = {"Apple", "Mandarin orange", "banana"};
Fruit[] fruitArray = new Fruit[strArray.length];
for(int i = 0; i < strArray.length; i++) {
fruitArray[i] = new Fruit(strArray[i]);
}
Fruit[] fruitArray = Arrays.stream(strArray) // (1)
.map(Fruit::new) // (2)
.toArray(Fruit[]::new); // (3)
(1) Convert from String array to String stream. (String [] ⇒ Stream \ <String >)
(2) Generate Fruit class for each Stream element with map method. Since there is only one String name argument in the constructor, this description is OK. (Of course, lambda expression s-> new Fruit (s) is also OK.)
(3) Convert to an array with the toArray method.
If you're not used to it, the for statement is easier to understand and write, but Once you get used to it, the code will be shorter and easier to write using the Stream API.
I'm still a beginner in Stream, so I want to force myself to get used to it quickly.
Recommended Posts