Java 8 Stream allows you to convert values to another type by using the Stream’s Map method and using Lambda. Instead of using loops to convert each iteam, we could use the power of functional programming readily available in Java 8.
[wp_ad_camp_1]
Change String to uppercase
1 2 3 4 5 | @Test public void test() { List<String> collected = Stream.of("a", "b", "hello").map(string -> string.toUpperCase()).collect(Collectors.toList()); Assert.assertEquals(Arrays.asList("A", "B", "HELLO"), collected); } |
Convert from one Java Bean to another
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | @Test public void testBean2Bean() { /** * Internal class used in the back-end. This could be your @Entity class * * @author TURRETA.COM * */ class PersonInternal { public PersonInternal(String name) { super(); this.name = name; } private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "PersonInternal [name=" + name + "]"; } } /** * External class used in the front-end. This could be whose instance you convert to JSON * * @author TURRETA.COM * */ class PersonExternalAPI { private String personName; public PersonExternalAPI(String personName) { super(); this.personName = personName; } public String getPersonName() { return personName; } public void setPersonName(String personName) { this.personName = personName; } @Override public String toString() { return "PersonExternalAPI [personName=" + personName + "]"; } } List<PersonExternalAPI> collected = Stream.of(new PersonInternal("Steve"), new PersonInternal("Owen")).map(pi -> { return new PersonExternalAPI(pi.getName()); }).collect(Collectors.toList()); collected.forEach(System.out::println); } |
This displays the following:
[wp_ad_camp_2]
1 2 | PersonExternalAPI [personName=Steve] PersonExternalAPI [personName=Owen] |