Created
November 4, 2015 15:03
-
-
Save stillerr/c15da909d742e525e2a6 to your computer and use it in GitHub Desktop.
Java 8, Lambdas and Anonymous Classes, ReactiveX fun
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test; | |
import com.google.common.collect.ArrayListMultimap; | |
import com.google.common.collect.Lists; | |
import com.google.common.collect.Maps; | |
import com.google.common.collect.Multimap; | |
import org.junit.Test; | |
import rx.Observable; | |
import rx.schedulers.Schedulers; | |
import java.util.Arrays; | |
import java.util.HashMap; | |
import java.util.List; | |
import java.util.Map; | |
import static rx.Observable.from; | |
import static rx.Observable.just; | |
public class TST { | |
@Test | |
public void testName() throws Exception { | |
final Map<Integer, String> objects = getObjects(); | |
final Multimap<String, Integer> bucket = getMap(); | |
just("D1", "D2", "D3") | |
.flatMap((key) -> just(getBucket(bucket, key))) | |
.flatMap((ids) -> getIds(ids, objects)) | |
.doOnNext(System.out::println) | |
.subscribe(); | |
} | |
private List getBucket(Multimap<String, Integer> bucket, String key) { | |
return Arrays.asList(bucket.get(key)); | |
} | |
private Observable<List<String>> getIds(List<Integer> ids, Map<Integer, String> objects) { | |
List<String> res = Lists.newArrayList(); | |
from(ids) | |
.subscribeOn(Schedulers.immediate()) | |
.map((i) -> { | |
String obj = objects.get(i); | |
if (obj == null) { | |
throw new RuntimeException("Unknown"); | |
} | |
return obj; | |
}) | |
.subscribe( | |
(element) -> { | |
res.add(element); | |
}, | |
(error) -> { | |
res.add("N/A"); | |
} | |
); | |
return just(res); | |
} | |
private Map<Integer, String> getObjects() { | |
HashMap<Integer, String> map = Maps.newHashMap(); | |
map.put(1, "Lorem"); | |
map.put(2, "Ipsum"); | |
map.put(3, "Dolor"); | |
map.put(5, "Amet"); | |
return map; | |
} | |
private Multimap<String, Integer> getMap() { | |
Multimap<String, Integer> bucket = ArrayListMultimap.create(); | |
bucket.putAll("D1", Lists.newArrayList(1, 3, 2)); | |
bucket.putAll("D2", Lists.newArrayList(2, 4)); | |
bucket.putAll("D3", Lists.newArrayList(1, 4, 5)); | |
return bucket; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment