@Test public void switchDisableInStream() { List<Integer> list = AnyM.fromStream(Stream.of(1, 2, 3)) .<Integer>bind(i -> i == 1 ? FeatureToggle.disable(i) : FeatureToggle.enable(i)) .asSequence() .toList(); assertThat(list, equalTo(Arrays.asList(2, 3))); }
@Test public void map() { StreamT<Integer> streamT = StreamT.of(AnyM.ofMonad(Optional.of(Stream.of(10)))); assertThat( streamT .map(num -> "hello world" + num) .unwrap() .<Optional<Stream<String>>>unwrap() .get() .collect(Collectors.toList()), equalTo(Arrays.asList("hello world10"))); }
@Test public void filterSuccess() { StreamT<Integer> streamT = StreamT.of(AnyM.ofMonad(Optional.of(Stream.of(10)))); assertThat( streamT .filter(num -> num == 10) .unwrap() .<Optional<Stream<String>>>unwrap() .get() .collect(Collectors.toList()), equalTo(Arrays.asList(10))); }
@Test public void peek() { result = null; StreamT<Integer> streamT = StreamT.of(AnyM.ofMonad(Optional.of(Stream.of(10)))); streamT .peek(num -> result = "hello world" + num) .unwrap() .<Optional<Stream<String>>>unwrap() .get() .collect(Collectors.toList()); assertThat(result, equalTo("hello world10")); }
@Test public void optionAndStream() { Function<Integer, Integer> add2 = i -> i + 2; Function<StreamT<Integer>, StreamT<Integer>> optTAdd2 = StreamT.lift(add2); Stream<Integer> nums = Stream.of(1, 2); AnyM<Stream<Integer>> stream = AnyM.fromOptional(Optional.of(nums)); List<Integer> results = optTAdd2 .apply(StreamT.of(stream)) .unwrap() .<Optional<Stream<Integer>>>unwrap() .get() .collect(Collectors.toList()); assertThat(results, equalTo(Arrays.asList(3, 4))); }
/** * Execute and Yield a result from this for comprehension using the supplied function * * <p>e.g. sum every element across nested structures * * <pre>{@code Do.add(list1) * .yield((Integer i1) -> i1); * * }</pre> * * @param f To be applied to every element in the for comprehension * @return For comprehension result */ public <R> AnyM<R> yield(Function<? super T1, R> f) { if (getOrgType() != null) return new MonadWrapper(this.yieldInternal(f), this.getOrgType()).anyM(); else return AnyM.ofMonad(this.yieldInternal(f)); }
/** @return This monad, wrapped as AnyM of Disabled */ public AnyM<F> anyMDisabled() { return AnyM.ofMonad(Optional.empty()); }
/** @return This monad, wrapped as AnyM */ public AnyM<F> anyM() { return AnyM.fromStreamable(this); }
@Test public void switchTest() { assertThat( AnyM.ofMonad(FeatureToggle.enable("hello world")).map(o -> "2" + o).asSequence().toList(), equalTo(Arrays.asList("2hello world"))); }