Exemplo n.º 1
1
 @Test
 public void shouldConvertToJavaStream() {
   final Value<Integer> value = of(1, 2, 3);
   final java.util.stream.Stream<Integer> s1 = value.toJavaStream();
   if (value.isSingleValued()) {
     final java.util.stream.Stream<Integer> s2 = java.util.stream.Stream.of(1);
     assertThat(List.ofAll(s1::iterator)).isEqualTo(List.ofAll(s2::iterator));
   } else {
     final java.util.stream.Stream<Integer> s2 = java.util.stream.Stream.of(1, 2, 3);
     assertThat(List.ofAll(s1::iterator)).isEqualTo(List.ofAll(s2::iterator));
   }
 }
Exemplo n.º 2
0
 /**
  * Given a list, this method will generate all combinations of multiset of this list. Example :
  *
  * <pre>combinationsMultiset(Arrays.asList("a", "c", "q"))</pre>
  *
  * <pre>
  * [a, c, q]
  * [c, q]
  * [a, q]
  * [a, c]
  * [q]
  * [c]
  * [a]
  * []
  * </pre>
  *
  * @param l The list.
  * @return All combination of multiset of the given list.
  */
 private static <E> Stream<List<E>> combinationsMultiset(List<E> l) {
   if (l.isEmpty()) {
     return Stream.of(Collections.emptyList());
   }
   return combinationsMultiset(l.subList(1, l.size()))
       .flatMap(t -> Stream.of(t, pipe(l.get(0), t)));
 }
  public void example() {
    System.out.println(
        Stream.of(IntStream.of(1), IntStream.of(2)).flatMapToInt((IntStream s) -> s).sum());

    // unchanged, it's not using the varargs overload
    System.out.println(Stream.of(IntStream.of(1)).flatMap(s -> s.boxed()).mapToInt(i -> i).sum());
  }
Exemplo n.º 4
0
  public static void main(String[] args) throws Exception {
    List<Integer> currentLocation = Arrays.asList(0, 0);

    Stream houses =
        Files.lines(new File("input.txt").toPath())
            .flatMap(line -> Stream.of(line.split("")))
            .map(
                s -> {
                  matchPath(s, currentLocation);
                  return new ArrayList<>(currentLocation);
                })
            .distinct();
    System.out.println(houses.count());

    List<Integer> santa = Arrays.asList(0, 0);
    List<Integer> robot = Arrays.asList(0, 0);
    List<String> paths =
        Files.lines(new File("input.txt").toPath())
            .flatMap(line -> Stream.of(line.split("")))
            .collect(Collectors.toList());
    Stream houses2 =
        IntStream.range(0, paths.size())
            .mapToObj(
                i -> {
                  if (i % 2 == 0) {
                    matchPath(paths.get(i), santa);
                  } else {
                    matchPath(paths.get(i), robot);
                  }
                  return Arrays.asList(santa, robot);
                })
            .flatMap(lists -> Stream.of(lists.get(0), lists.get(1)))
            .distinct();
    System.out.println(houses2.count());
  }
Exemplo n.º 5
0
  public static void main(String[] args) throws IOException {
    Path path = Paths.get("../alice.txt");
    String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

    Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));
    show("words", words);
    Stream<String> song = Stream.of("gently", "down", "the", "stream");
    show("song", song);
    Stream<String> silence = Stream.empty();
    silence = Stream.<String>empty(); // Explicit type specification
    show("silence", silence);

    Stream<String> echos = Stream.generate(() -> "Echo");
    show("echos", echos);

    Stream<Double> randoms = Stream.generate(Math::random);
    show("randoms", randoms);

    Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
    show("integers", integers);

    Stream<String> wordsAnotherWay = Pattern.compile("[\\P{L}]+").splitAsStream(contents);
    show("wordsAnotherWay", wordsAnotherWay);

    try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
      show("lines", lines);
    }
  }
Exemplo n.º 6
0
 public static void main(String[] args) {
   Personne[] tab = {
     new Personne("thibault", "Rougier", 2001),
     new Personne("thomas", "Niesseron", 1987),
     new Personne("thifaine", "Mitenne", 1959),
     new Personne("maxime", "Forest", 1995),
     new Personne("jules", "Forest", 1995)
   };
   System.out.println("--- Nes apres 1985 : ");
   Stream.of(tab)
       .filter(pp -> pp.getAnnee() > 1985)
       .forEach(pp -> System.out.print(pp.getPrenom() + ", "));
   System.out.println("\n--- Nes avant 2000 :");
   long nombre =
       Stream.of(tab)
           .filter(pp -> pp.getAnnee() < 2000)
           .sorted(Comparator.comparing(Personne::getNom))
           .peek(pp -> System.out.print(pp.getNom() + " "))
           .count();
   System.out.println("\n       Ils sont " + nombre);
   System.out.println("--- Tous tries sur nom + prenom : ");
   Stream.of(tab)
       .sorted(Comparator.comparing(pp -> pp.getNom() + pp.getPrenom()))
       .forEach(pp -> System.out.print("(" + pp.getNom() + ", " + pp.getPrenom() + ") "));
 }
Exemplo n.º 7
0
  @Override
  public Iterator<Edge> edges(final Object... edgeIds) {
    try {
      if (0 == edgeIds.length) {
        return new HadoopEdgeIterator(this);
      } else {
        // base the conversion function on the first item in the id list as the expectation is that
        // these
        // id values will be a uniform list
        if (edgeIds[0] instanceof Edge) {
          // based on the first item assume all Edges in the argument list
          if (!Stream.of(edgeIds).allMatch(id -> id instanceof Edge))
            throw Graph.Exceptions.idArgsMustBeEitherIdOrElement();

          // no need to get the vertices again, so just flip it back - some implementation may want
          // to treat this
          // as a refresh operation. that's not necessary for hadoopgraph.
          return Stream.of(edgeIds).map(id -> (Edge) id).iterator();
        } else {
          final Class<?> firstClass = edgeIds[0].getClass();
          if (!Stream.of(edgeIds).map(Object::getClass).allMatch(firstClass::equals))
            throw Graph.Exceptions
                .idArgsMustBeEitherIdOrElement(); // todo: change exception to be ids of the same
                                                  // type
          return IteratorUtils.filter(
              new HadoopEdgeIterator(this), vertex -> ElementHelper.idExists(vertex.id(), edgeIds));
        }
      }
    } catch (final IOException e) {
      throw new IllegalStateException(e.getMessage(), e);
    }
  }
Exemplo n.º 8
0
 @SuppressWarnings("unchecked")
 private static <T> T instantiate(
     Class<T> clazz, List<Class<?>> matchingClasses, Object... preInstancedDependencies) {
   try {
     logger.info("Creating instance of: " + clazz);
     Constructor<?> clazzConstructor = Stream.of(clazz.getConstructors()).findFirst().get();
     Class<?>[] parameterTypes = clazzConstructor.getParameterTypes();
     if (parameterTypes.length > 0) {
       Object[] paramInstances =
           Stream.of(parameterTypes)
               .map(
                   paramType ->
                       Stream.of(preInstancedDependencies)
                           .filter(obj -> paramType.isInstance(obj))
                           .findFirst()
                           .orElseGet(
                               () ->
                                   instantiate(
                                       paramType, matchingClasses, preInstancedDependencies)))
               .toArray();
       return (T) clazzConstructor.newInstance(paramInstances);
     } else {
       return clazz.newInstance();
     }
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
Exemplo n.º 9
0
 private static Map<String, Method> addMethods(
     Map<String, Method> methods, Class<?> clazz, Predicate<Method> filter) {
   requireNonNull(methods);
   requireNonNull(filter);
   // clazz nullable (why?)
   if (clazz == Object.class) {
     return methods;
   }
   if (clazz == null) {
     return methods;
   }
   Stream.of(clazz.getDeclaredMethods())
       .filter(filter)
       .forEach(
           m -> {
             methods.putIfAbsent(m.getName(), m); // Put only the most recent
             // concrete version of the
             // method
           });
   addMethods(methods, clazz.getSuperclass(), filter); // Recursively add
   // the superclass
   // methods
   Stream.of(clazz.getInterfaces())
       .forEach(
           i -> {
             addMethods(methods, i, filter); // Recursively add the extended
             // interfaces (because they can
             // contain default methods)
           });
   return methods;
 }
  public static void main(String[] args) {

    // stream.collect(collector): values
    // Collectors.groupingBy(classifier)
    Stream<Locale> locales = Stream.of(Locale.getAvailableLocales());
    Map<String, List<Locale>> languageToLocales =
        locales.collect(Collectors.groupingBy(Locale::getDisplayLanguage));
    System.out.println(languageToLocales);

    System.out.println("--------------");

    // stream.collect(collector): values
    // Collectors.groupingBy(classifier, downstream)
    locales = Stream.of(Locale.getAvailableLocales());
    Map<String, Long> languageToLocalesCounting =
        locales.collect(Collectors.groupingBy(Locale::getDisplayLanguage, Collectors.counting()));
    System.out.println(languageToLocalesCounting);

    System.out.println("--------------");

    // stream.collect(collector): values
    // Collectors.partitioningBy(predicate)
    locales = Stream.of(Locale.getAvailableLocales());
    Map<Boolean, List<Locale>> englishAndOtherLocales =
        locales.collect(Collectors.partitioningBy(l -> l.getLanguage().equals("en")));
    List<Locale> englishLocales = englishAndOtherLocales.get(true);
    System.out.println(englishLocales);

    System.out.println("--------------");
  }
Exemplo n.º 11
0
  @Test
  public void testConsumers() {
    final AtomicLong lc = new AtomicLong(0L);
    Assert.assertEquals(Anoa.of(1L), handler.consumer(lc::addAndGet).apply(handler.of(1L)));
    Assert.assertEquals(1L, lc.get());
    Assert.assertEquals(
        Anoa.empty(Stream.of(Meta.OTHER)),
        handler
            .consumerChecked(
                __ -> {
                  throw new IOException();
                })
            .apply(handler.of(1L)));

    final AtomicLong lc2 = new AtomicLong(0L);
    Assert.assertEquals(
        Anoa.of(1L),
        handler.biConsumer((Long x, Long y) -> lc2.addAndGet(x + y)).apply(Anoa.of(1L), 1L));
    Assert.assertEquals(2L, lc2.get());

    Assert.assertEquals(
        Anoa.empty(Stream.of(Meta.OTHER)),
        handler
            .biConsumerChecked(
                (_1, _2) -> {
                  throw new IOException();
                })
            .apply(Anoa.of(1L), 1L));
  }
Exemplo n.º 12
0
  @Test
  public void testFunctions() {
    final AtomicLong lf = new AtomicLong(10L);
    Assert.assertEquals(Anoa.of(10L), handler.function(lf::getAndAdd).apply(handler.of(1L)));
    Assert.assertEquals(11L, lf.get());
    Assert.assertEquals(
        Anoa.empty(Stream.of(Meta.OTHER)),
        handler
            .functionChecked(
                __ -> {
                  throw new IOException();
                })
            .apply(handler.of(1L)));

    final AtomicLong lf2 = new AtomicLong(10L);
    Assert.assertEquals(
        Anoa.of(10L),
        handler.biFunction((Long x, Long y) -> lf2.getAndAdd(x + y)).apply(Anoa.of(1L), 1L));
    Assert.assertEquals(12L, lf2.get());

    Assert.assertEquals(
        Anoa.empty(Stream.of(Meta.OTHER)),
        handler
            .biFunctionChecked(
                (_1, _2) -> {
                  throw new IOException();
                })
            .apply(Anoa.of(1L), 1L));
  }
Exemplo n.º 13
0
  public static void main(String[] args) {

    // An Operation on a stream that returns a stream is an intermediary operation

    Stream<String> stream1 = Stream.of("one", "two", "three", "four", "five");
    Predicate<String> p1 = Predicate.isEqual("two");
    stream1.filter(p1); // This is an intermediary operation and it does nothing!

    /*
       The below piece of code does nothing!
       peek() and filter() methods are intermediary operations as they return a stream.
       Hence, this code does not prints anything.
       It is just a simple declaration.
    */
    List<String> result1 = new ArrayList<>();
    Stream<String> stream2 = Stream.of("one", "two", "three", "four", "five");
    Predicate<String> p2 = Predicate.isEqual("two");
    stream2.peek(System.out::println).filter(p2).peek(result1::add);
    System.out.println("size -> " + result1.size());

    System.out.println("******************************************");
    /*
       Using Final method (forEach())
       Only the Final operation triggers the processing of the data the stream is connected to.
    */
    List<String> result2 = new ArrayList<>();
    Stream<String> stream3 = Stream.of("one", "two", "three", "four", "five");
    Predicate<String> p3 = Predicate.isEqual("two");
    Predicate<String> p4 = Predicate.isEqual("three");
    stream3.peek(System.out::println).filter(p3.or(p4)).forEach(result2::add);
    System.out.println("size -> " + result2.size());
  }
Exemplo n.º 14
0
 /**
  * @param collector to perform aggregation / reduction operation on the results from active stage
  *     (e.g. to Collect into a List or String)
  * @param fn Function that receives the results of all currently active tasks as input
  * @return A new builder object that can be used to define the next stage in the dataflow
  */
 @SuppressWarnings({"unchecked", "rawtypes"})
 default <T, R> SimpleReactStream<R> allOf(final Collector collector, final Function<T, R> fn) {
   CompletableFuture[] array = lastActiveArray(getLastActive());
   CompletableFuture cf = CompletableFuture.allOf(array);
   Function<Exception, T> f =
       (Exception e) -> {
         BlockingStreamHelper.capture(e, getErrorHandler());
         return BlockingStreamHelper.block(
             this, Collectors.toList(), new StreamWrapper(Stream.of(array), true));
       };
   CompletableFuture onFail = cf.exceptionally(f);
   CompletableFuture onSuccess =
       onFail.thenApplyAsync(
           (result) -> {
             return new StageWithResults(this.getTaskExecutor(), null, result)
                 .submit(
                     () ->
                         (R)
                             fn.apply(
                                 BlockingStreamHelper.aggregateResults(
                                     collector,
                                     Stream.of(array).collect(Collectors.toList()),
                                     getErrorHandler())));
           },
           getTaskExecutor());
   return (SimpleReactStream<R>) withLastActive(new StreamWrapper(onSuccess, isEager()));
 }
Exemplo n.º 15
0
  private void afterDeploymentValidation(
      @Observes AfterDeploymentValidation adv, BeanManager manager) {
    Collection<CamelContext> contexts = new ArrayList<>();
    for (Bean<?> context : manager.getBeans(CamelContext.class, ANY)) {
      contexts.add(getReference(manager, CamelContext.class, context));
    }

    // Add type converters to Camel contexts
    CdiTypeConverterLoader loader = new CdiTypeConverterLoader();
    for (Class<?> converter : converters) {
      for (CamelContext context : contexts) {
        loader.loadConverterMethods(context.getTypeConverterRegistry(), converter);
      }
    }

    // Add routes to Camel contexts
    boolean deploymentException = false;
    Set<Bean<?>> routes = new HashSet<>(manager.getBeans(RoutesBuilder.class, ANY));
    routes.addAll(manager.getBeans(RouteContainer.class, ANY));
    for (Bean<?> context : manager.getBeans(CamelContext.class, ANY)) {
      for (Bean<?> route : routes) {
        Set<Annotation> qualifiers = new HashSet<>(context.getQualifiers());
        qualifiers.retainAll(route.getQualifiers());
        if (qualifiers.size() > 1) {
          deploymentException |= !addRouteToContext(route, context, manager, adv);
        }
      }
    }
    // Let's return to avoid starting misconfigured contexts
    if (deploymentException) {
      return;
    }

    // Trigger eager beans instantiation (calling toString is necessary to force
    // the initialization of normal-scoped beans).
    // FIXME: This does not work with OpenWebBeans for bean whose bean type is an
    // interface as the Object methods does not get forwarded to the bean instances!
    eagerBeans.forEach(type -> getReferencesByType(manager, type.getJavaClass(), ANY).toString());
    manager
        .getBeans(Object.class, ANY, STARTUP)
        .stream()
        .forEach(bean -> getReference(manager, bean.getBeanClass(), bean).toString());

    // Start Camel contexts
    for (CamelContext context : contexts) {
      if (ServiceStatus.Started.equals(context.getStatus())) {
        continue;
      }
      logger.info("Camel CDI is starting Camel context [{}]", context.getName());
      try {
        context.start();
      } catch (Exception exception) {
        adv.addDeploymentProblem(exception);
      }
    }

    // Clean-up
    Stream.of(converters, camelBeans, eagerBeans, cdiBeans).forEach(Set::clear);
    Stream.of(producerBeans, producerQualifiers).forEach(Map::clear);
  }
Exemplo n.º 16
0
 protected OptionalEntity<FileConfig> getFileConfig(final CreateForm form) {
   final String username = systemHelper.getUsername();
   final long currentTime = systemHelper.getCurrentTimeAsLong();
   return getEntity(form, username, currentTime)
       .map(
           entity -> {
             entity.setUpdatedBy(username);
             entity.setUpdatedTime(currentTime);
             copyBeanToBean(
                 form,
                 entity,
                 op ->
                     op.exclude(
                         Stream.concat(
                                 Stream.of(Constants.COMMON_CONVERSION_RULE),
                                 Stream.of(Constants.PERMISSIONS))
                             .toArray(n -> new String[n])));
             final PermissionHelper permissionHelper = ComponentUtil.getPermissionHelper();
             entity.setPermissions(
                 split(form.permissions, "\n")
                     .get(
                         stream ->
                             stream
                                 .map(s -> permissionHelper.encode(s))
                                 .filter(StringUtil::isNotBlank)
                                 .distinct()
                                 .toArray(n -> new String[n])));
             return entity;
           });
 }
Exemplo n.º 17
0
  public ResearchNode(String name, NodeState defState, ResearchNode... pre) {
    this.name = name;
    defaultState = defState;
    dependencies = Stream.of(pre).map(ResearchNode::getName).collect(Collectors.toList());
    dependants = new ArrayList<>();

    Stream.of(pre).forEach(n -> n.addDependant(this));
  }
Exemplo n.º 18
0
  @Test
  public void collectCombinedArrayWhenStreamCombinedWithAnotherInParallel() throws Exception {
    NSArray<String> result =
        concat(Stream.of("test1").parallel(), Stream.of("test2").parallel()).collect(toNSArray());

    assertThat(result.size(), is(2));
    assertThat(result, hasItems("test1", "test2"));
  }
Exemplo n.º 19
0
  public static void main(String... args) {

    /*
    -------------------------------------------------------------------------
    From obj to ...
    -------------------------------------------------------------------------
    */
    Stream<String> streamOfStrings = Stream.of("un", "deux", "trois");
    Function<String, StringBuilder> function = StringBuilder::new;
    streamOfStrings.map(function) /*.forEach(System.out::println)*/;
    streamOfStrings = Stream.of("un", "deux", "trois");
    ToIntFunction<String> toIntFunction = String::length;
    IntStream streamOfInts = streamOfStrings.mapToInt(toIntFunction);
    streamOfStrings = Stream.of("un", "deux", "trois");
    ToDoubleFunction<String> toDoubleFunction = String::length;
    DoubleStream streamOfDoubles = streamOfStrings.mapToDouble(toDoubleFunction);
    streamOfStrings = Stream.of("un", "deux", "trois");
    ToLongFunction<String> toLongFunction = String::length;
    LongStream streamOfLongs = streamOfStrings.mapToLong(toLongFunction);

    /*
    -------------------------------------------------------------------------
    From int to ...
    -------------------------------------------------------------------------
    */
    IntUnaryOperator plusplus = i -> i++;
    IntStream.of(1, 2, 3).map(plusplus)
    /*.forEach(x->System.out.println(x))*/ ;
    IntFunction<String> intFunction = i -> "" + i;
    IntStream.of(1, 2, 3).mapToObj(intFunction)
    /*.forEach(System.out::println)*/ ;
    IntToDoubleFunction itdf = i -> i;
    IntStream.of(1, 2, 3).mapToDouble(itdf)
    /*.forEach(System.out::println)*/ ;
    IntToLongFunction itlf = i -> i;
    IntStream.of(1, 2, 3).mapToLong(itlf)
    /*.forEach(System.out::println)*/ ;

    /*
    -------------------------------------------------------------------------
    From long to ...
    -------------------------------------------------------------------------
    */
    LongUnaryOperator times = l -> l * l;
    LongStream.of(1L, 2L, 3L).map(times)
    /*.forEach(System.out::println)*/ ;
    LongFunction<String> lf = l -> "toto";
    LongStream.of(1L, 2L, 3L).mapToObj(lf);

    /*
    -------------------------------------------------------------------------
    From double to ...
    -------------------------------------------------------------------------
    */
    DoubleToIntFunction dtif = d -> (int) d;
    DoubleStream.of(1.3, 1.5, 1.6).mapToInt(dtif).forEach(System.out::println);
  }
Exemplo n.º 20
0
  @Test
  public void testZip() {
    Stream<Predicate<Integer>> predicates = Stream.of(i -> true, i -> false);
    Stream<Function<Integer, Integer>> functions = Stream.of(i -> i + 2, i -> i * 100);

    val cases = Cases.zip(predicates, functions);
    assertThat(cases.size(), is(2));
    assertThat(cases.match(100).get(), is(102));
  }
Exemplo n.º 21
0
public class BuiltinDerivator {

  private static final Function<Make, Stream<Make>> dependencies =
      Makes.cases()
          .lambdaVisitor(Stream::<Make>of)
          .constructors(Stream::of)
          .lazyConstructor(Stream::of)
          .patternMatching(() -> Stream.of(lambdaVisitor))
          .getters(() -> Stream.of(lambdaVisitor))
          .modifiers(() -> Stream.of(lambdaVisitor, constructors))
          .catamorphism(() -> Stream.of(lambdaVisitor))
          .hktCoerce(Stream::of);

  public static BiFunction<AlgebraicDataType, DeriveContext, DeriveResult<DerivedCodeSpec>>
      derivator(DeriveUtils deriveUtils) {

    return (adt, deriveContext) ->
        traverseResults(
                deriveContext.makes(),
                Makes.cases()
                    .lambdaVisitor(
                        lazy(() -> MapperDerivator.derive(adt, deriveContext, deriveUtils)))
                    .constructors(
                        lazy(
                            () ->
                                StrictConstructorDerivator.derive(adt, deriveContext, deriveUtils)))
                    .lazyConstructor(
                        lazy(
                            () -> LazyConstructorDerivator.derive(adt, deriveContext, deriveUtils)))
                    .patternMatching(
                        lazy(
                            () -> PatternMatchingDerivator.derive(adt, deriveContext, deriveUtils)))
                    .getters(lazy(() -> GettersDerivator.derive(adt, deriveContext, deriveUtils)))
                    .modifiers(lazy(() -> ModiersDerivator.derive(adt, deriveContext, deriveUtils)))
                    .catamorphism(
                        lazy(() -> new CataDerivator(deriveUtils, deriveContext, adt).derive()))
                    .hktCoerce(DeriveResult.result(DerivedCodeSpec.none())))
            .map(
                codeSpecList ->
                    codeSpecList.stream().reduce(DerivedCodeSpec.none(), DerivedCodeSpec::append));
  }

  public static Set<Make> makeWithDpendencies(Make... makes) {

    EnumSet<Make> makeSet = EnumSet.noneOf(Make.class);

    makeSet.addAll(
        Arrays.asList(makes)
            .stream()
            .flatMap(m -> Stream.concat(dependencies.apply(m), Stream.of(m)))
            .collect(Collectors.toList()));

    return Collections.unmodifiableSet(makeSet);
  }
}
Exemplo n.º 22
0
  @Test
  public void _02_스트림_생성() {
    // 배열로 부터~
    Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));

    // 가변 인자로..
    Stream<String> song = Stream.of("gently", "down", "the", "stream");

    // 빈 스트림
    Stream<String> silence = Stream.empty();
  }
Exemplo n.º 23
0
  TypeName cataMapperTypeName(DataConstructor dc) {

    TypeName[] argsTypeNames =
        concat(
                dc.arguments().stream().map(DataArgument::type),
                dc.typeRestrictions()
                    .stream()
                    .map(TypeRestriction::idFunction)
                    .map(DataArgument::type))
            .map(t -> Utils.asBoxedType.visit(t, utils.types()))
            .map(this::substituteTypeWithRecursionVar)
            .map(TypeName::get)
            .toArray(TypeName[]::new);

    return adt.dataConstruction().isVisitorDispatch()
        ? argsTypeNames.length == 0
            ? ParameterizedTypeName.get(
                ClassName.get(FlavourImpl.findF0(context.flavour(), utils.elements())),
                TypeName.get(adt.matchMethod().returnTypeVariable()))
            : argsTypeNames.length == 1
                ? ParameterizedTypeName.get(
                    ClassName.get(FlavourImpl.findF(context.flavour(), utils.elements())),
                    argsTypeNames[0],
                    TypeName.get(adt.matchMethod().returnTypeVariable()))
                : ParameterizedTypeName.get(
                    Utils.getClassName(context, MapperDerivator.mapperInterfaceName(dc)),
                    concat(
                            concat(
                                dc.typeVariables().stream().map(TypeVariableName::get),
                                fold(
                                    MapperDerivator.findInductiveArgument(utils, adt, dc),
                                    Stream.<TypeName>of(),
                                    tm ->
                                        Stream.of(
                                            ParameterizedTypeName.get(
                                                ClassName.get(
                                                    FlavourImpl.findF0(
                                                        context.flavour(), utils.elements())),
                                                TypeName.get(
                                                    adt.matchMethod().returnTypeVariable()))))),
                            Stream.of(TypeVariableName.get(adt.matchMethod().returnTypeVariable())))
                        .toArray(TypeName[]::new))
        : TypeName.get(
            utils
                .types()
                .getDeclaredType(
                    Utils.asTypeElement.visit(dc.deconstructor().visitorType().asElement()).get(),
                    dc.deconstructor()
                        .visitorType()
                        .getTypeArguments()
                        .stream()
                        .map(this::substituteTypeWithRecursionVar)
                        .toArray(TypeMirror[]::new)));
  }
 @Test
 public void findAllStream() {
   Object id0 = "id0";
   Object id1 = "id1";
   Entity entity0 = mock(Entity.class);
   Entity entity1 = mock(Entity.class);
   Stream<Object> entityIds = Stream.of(id0, id1);
   when(decoratedRepository.findAll(entityIds)).thenReturn(Stream.of(entity0, entity1));
   Stream<Entity> expectedEntities = entityListenerRepositoryDecorator.findAll(entityIds);
   assertEquals(expectedEntities.collect(Collectors.toList()), Arrays.asList(entity0, entity1));
 }
Exemplo n.º 25
0
  public static void main(String[] args) {
    // check args
    Stream.of(args).forEach(System.out::println);

    // check .
    Stream.of(new File(".").list()).forEach(System.out::println);

    // check external libs
    Client client = ClientBuilder.newClient();
    String response = client.target("https://api.github.com/zen").request().get(String.class);
    System.out.println(response);
  }
Exemplo n.º 26
0
  public static void main(String[] args) {
    // 스트림 생성
    Stream<String> song = Stream.of("gently", "down", "the", "stream");

    // 난수 100개
    Stream<Double> randoms = Stream.generate(Math::random).limit(100);

    //
    Stream<String> uniqueWords = Stream.of("merrily", "merrily", "merrily", "gentyl").distinct();

    Stream<Double> greatFirst =
        randoms.sorted(Comparator.comparing(Double::doubleValue).reversed());
    greatFirst.forEach(System.out::println);
  }
Exemplo n.º 27
0
  public static void main(String[] args) {
    Integer[] array = new Integer[] {1, 2, 3};
    System.out.println("============");
    Stream.of(array).forEach(System.out::println);

    Sec02.swap(array, 0, 1);
    System.out.println("============");

    Stream.of(array).forEach(System.out::println);

    Sec02.<Integer>swap(array, 1, 2);
    System.out.println("============");
    Stream.of(array).forEach(System.out::println);
  }
  private Mono<Object[]> resolveArguments(
      ServerWebExchange exchange, BindingContext bindingContext, Object... providedArgs) {

    if (ObjectUtils.isEmpty(getMethodParameters())) {
      return NO_ARGS;
    }
    try {
      List<Mono<Object>> monos =
          Stream.of(getMethodParameters())
              .map(
                  param -> {
                    param.initParameterNameDiscovery(this.parameterNameDiscoverer);
                    GenericTypeResolver.resolveParameterType(param, getBean().getClass());
                    if (!ObjectUtils.isEmpty(providedArgs)) {
                      for (Object providedArg : providedArgs) {
                        if (param.getParameterType().isInstance(providedArg)) {
                          return Mono.just(providedArg).log("reactor.resolved");
                        }
                      }
                    }
                    HandlerMethodArgumentResolver resolver =
                        this.resolvers
                            .stream()
                            .filter(r -> r.supportsParameter(param))
                            .findFirst()
                            .orElseThrow(() -> getArgError("No resolver for ", param, null));
                    try {
                      return resolver
                          .resolveArgument(param, bindingContext, exchange)
                          .defaultIfEmpty(NO_VALUE)
                          .doOnError(
                              cause -> {
                                if (logger.isDebugEnabled()) {
                                  logger.debug(
                                      getDetailedErrorMessage("Error resolving ", param), cause);
                                }
                              })
                          .log("reactor.unresolved");
                    } catch (Exception ex) {
                      throw getArgError("Error resolving ", param, ex);
                    }
                  })
              .collect(Collectors.toList());

      // Create Mono with array of resolved values...
      return Mono.when(monos, args -> Stream.of(args).map(o -> o != NO_VALUE ? o : null).toArray());
    } catch (Throwable ex) {
      return Mono.error(ex);
    }
  }
 @Test
 public void findAllStreamFetch() {
   Fetch fetch = new Fetch();
   Object id0 = "id0";
   Object id1 = "id1";
   Entity entity0 = Mockito.mock(Entity.class);
   Entity entity1 = Mockito.mock(Entity.class);
   Stream<Object> entityIds = Stream.of(id0, id1);
   Mockito.when(decoratedRepository.findAll(entityIds, fetch))
       .thenReturn(Stream.of(entity0, entity1));
   Stream<Entity> expectedEntities = entityListenerRepositoryDecorator.findAll(entityIds, fetch);
   Assert.assertEquals(
       expectedEntities.collect(Collectors.toList()), Arrays.asList(entity0, entity1));
 }
Exemplo n.º 30
0
 @Test
 public void testPredicates() {
   Assert.assertEquals(
       Anoa.empty(Stream.of(Meta.FAIL)),
       handler.predicate(__ -> false, __ -> Stream.of(Meta.FAIL)).apply(Anoa.of(1L)));
   Assert.assertEquals(
       Anoa.empty(Stream.of(Meta.OTHER)),
       handler
           .predicateChecked(
               __ -> {
                 throw new IOException();
               },
               __ -> Stream.of(Meta.FAIL))
           .apply(Anoa.of(1L)));
 }