1. reverse 구현
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> result = numbers.stream()
.collect(new ReverseCollector<>());
System.out.println(result); // [5, 4, 3, 2, 1]
}
package modernjavainaction.chap06;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class ReverseCollector<T> implements Collector<T,List<T>,List<T>> {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1,2,3,4,5);
List<Integer> result = numbers.stream().collect(new ReverseCollector<Integer>());
System.out.println(result);
}
@Override
public Supplier<List<T>> supplier() {
return ArrayList::new;
}
@Override
public BiConsumer<List<T>, T> accumulator() {
BiConsumer<List<T>,T> d = (list, item) -> {
list.add(0, item);
};
return d;
}
@Override
public BinaryOperator<List<T>> combiner() {
return (list1, list2) -> {
list1.addAll(list2);
return list1;
};
}
@Override
public Function<List<T>, List<T>> finisher() {
return Function.identity();
}
@Override
public Set<Characteristics> characteristics() {
return Collections.unmodifiableSet(EnumSet
.of(Characteristics.IDENTITY_FINISH,Characteristics.CONCURRENT));
}
}
2. String concat 구현
public static void main(String[] args) {
List<String> words = Arrays.asList("Hello", " ", "world", "!");
String result = words.stream()
.collect(new StringConcatCollector());
System.out.println(result); // Hello world!
}
package modernjavainaction.chap06;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
public class StringConcatCollector implements Collector<CharSequence,StringBuilder,String> {
public static void main(String[] args) {
List<String> words = Arrays.asList("Hello", " ", "world","!");
String result = words.stream().collect(new StringConcatCollector());
System.out.println(result);
}
@Override
public Supplier<StringBuilder> supplier() {
return StringBuilder::new;
}
@Override
public BiConsumer<StringBuilder, CharSequence> accumulator() {
return StringBuilder::append;
}
@Override
public BinaryOperator<StringBuilder> combiner() {
return (sb1, sb2) -> {sb1.append(sb2); return sb1;};
}
@Override
public Function<StringBuilder, String> finisher() {
return StringBuilder::toString;
}
@Override
public Set<Characteristics> characteristics() {
return Collections.emptySet();
}
}
'스터디' 카테고리의 다른 글
[모던 자바 인 액션] 8장. 개선된 컬렉션 API (0) | 2023.07.28 |
---|---|
[오브젝트] 3장. 역할, 책임, 협력 (0) | 2023.07.27 |
[모던 자바 인 액션] 7장. 병렬 데이터 처리와 성능 (0) | 2023.07.21 |
[객체지향의 사실과 오해] 6장 객체지도, 7장 함께 모으기 (0) | 2023.07.07 |
[모던 자바 인 액션] 스트림 활용 - faltMap, takeWhile, doWhile, reduce (0) | 2023.07.07 |
댓글