Rxjava를 써 본지가 너무 오래되어서 기억이 가물가물한데, 찾아보니
https://reactivex.io/documentation/operators/groupby.html
RxJava는 스트림으로 동작을 하므로, groiupBy를 통해 님이 생각하는 상태의 값을 얻으려면 groupBy 후에 정렬된 상태가 되도록 collect를 해주어야 합니다.
아래처럼 groupBy 후에, flatMap을 통해 collect해주는 과정이 필요합니다.
List<String> whiteListedGroup = Arrays.asList("A", "B", "C");
Observable.just(
"A1", "B1", "B2",
"A2", "C1", "C2",
"A3", "B3", "C3")
.groupBy(item -> {
String groupName = item.substring(0, 1);
return whiteListedGroup.contains(groupName) ? groupName : "None";
})
.flatMapSingle(f -> f.collect(
// (Callable<Map<String, List<String>>>)
() -> Collections.singletonMap(f.getKey(), new ArrayList<String>()),
// (BiConsumer<Map<String, List<String>>, String>)
(m, s) -> m.get(f.getKey()).add(s)
))
.subscribe(g -> {
System.out.println(g);
});
단순히 colletion을 가지고 groupBy를 할거라면 Java8의 stream api가 더 합리적인 선택이지만, 네트워크 호출 같은 걸 해야 한다면, RxJava를 통하는 것이 더 적합한 것 같습니다.