|
| 1 | +package com.baeldung.list; |
| 2 | + |
| 3 | +import java.util.ArrayList; |
| 4 | +import java.util.Collections; |
| 5 | +import java.util.List; |
| 6 | +import java.util.Optional; |
| 7 | +import java.util.stream.Collectors; |
| 8 | +import java.util.stream.Stream; |
| 9 | + |
| 10 | +public class CopyListService { |
| 11 | + |
| 12 | + public List<Flower> copyListByConstructor(List<Flower> source) { |
| 13 | + return new ArrayList<Flower>(source); |
| 14 | + } |
| 15 | + |
| 16 | + public List<Flower> copyListByConstructorAndEditOneFlowerInTheNewList(List<Flower> source) { |
| 17 | + List<Flower> flowers = new ArrayList<>(source); |
| 18 | + if(flowers.size() > 0) { |
| 19 | + flowers.get(0).setPetals(flowers.get(0).getPetals() * 3); |
| 20 | + } |
| 21 | + |
| 22 | + return flowers; |
| 23 | + } |
| 24 | + |
| 25 | + public List<Flower> copyListByAddAllMethod(List<Flower> source) { |
| 26 | + List<Flower> flowers = new ArrayList<>(); |
| 27 | + flowers.addAll(source); |
| 28 | + return flowers; |
| 29 | + } |
| 30 | + |
| 31 | + public List<Flower> copyListByAddAllMethodAndEditOneFlowerInTheNewList(List<Flower> source) { |
| 32 | + List<Flower> flowers = new ArrayList<>(); |
| 33 | + flowers.addAll(source); |
| 34 | + |
| 35 | + if(flowers.size() > 0) { |
| 36 | + flowers.get(0).setPetals(flowers.get(0).getPetals() * 3); |
| 37 | + } |
| 38 | + |
| 39 | + return flowers; |
| 40 | + } |
| 41 | + |
| 42 | + public List<Integer> copyListByCopyMethod(List<Integer> source, List<Integer> dest) { |
| 43 | + Collections.copy(dest, source); |
| 44 | + return dest; |
| 45 | + } |
| 46 | + |
| 47 | + public List<Flower> copyListByStream(List<Flower> source) { |
| 48 | + return source.stream().collect(Collectors.toList()); |
| 49 | + } |
| 50 | + |
| 51 | + public List<Flower> copyListByStreamAndSkipFirstElement(List<Flower> source) { |
| 52 | + return source.stream().skip(1).collect(Collectors.toList()); |
| 53 | + } |
| 54 | + |
| 55 | + public List<Flower> copyListByStreamWithFilter(List<Flower> source, Integer moreThanPetals) { |
| 56 | + return source.stream().filter(f -> f.getPetals() > moreThanPetals).collect(Collectors.toList()); |
| 57 | + } |
| 58 | + |
| 59 | + public List<Flower> copyListByStreamWithOptional(List<Flower> source) { |
| 60 | + return Optional.ofNullable(source) |
| 61 | + .map(List::stream) |
| 62 | + .orElseGet(Stream::empty) |
| 63 | + .collect(Collectors.toList()); |
| 64 | + } |
| 65 | + |
| 66 | + public List<Flower> copyListByStreamWithOptionalAndSkip(List<Flower> source) { |
| 67 | + return Optional.ofNullable(source) |
| 68 | + .map(List::stream) |
| 69 | + .orElseGet(Stream::empty) |
| 70 | + .skip(1) |
| 71 | + .collect(Collectors.toList()); |
| 72 | + } |
| 73 | +} |
0 commit comments