java.util.stream.Stream Java Examples

The following examples show how to use java.util.stream.Stream. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ShiftingWindowSummarizingLongTest.java    From streams-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void should_summarize_a_non_empty_stream_with_correct_substreams_content() {
    // Given
    Stream<String> strings = Stream.of("2", "4", "2", "4", "2", "4", "2");
    int groupingFactor = 2;
    LongSummaryStatistics stats = new LongSummaryStatistics();
    stats.accept(2L);
    stats.accept(4L);

    // When
    Stream<LongSummaryStatistics> summarizedStream = StreamsUtils.shiftingWindowSummarizingLong(strings, groupingFactor, Long::parseLong);
    List<LongSummaryStatistics> result = summarizedStream.collect(toList());

    // When
    assertThat(result.size()).isEqualTo(6);
    assertThat(result.get(0).toString()).isEqualTo(stats.toString());
    assertThat(result.get(1).toString()).isEqualTo(stats.toString());
    assertThat(result.get(2).toString()).isEqualTo(stats.toString());
    assertThat(result.get(3).toString()).isEqualTo(stats.toString());
    assertThat(result.get(4).toString()).isEqualTo(stats.toString());
    assertThat(result.get(5).toString()).isEqualTo(stats.toString());
}
 
Example #2
Source File: DBServiceTest.java    From amdb-proxy with Apache License 2.0 6 votes vote down vote up
@Test
void testInfo() throws IOException {
  Request<InfoRequest> request = new Request<InfoRequest>();
  request.setOp("info");

  InfoRequest params = new InfoRequest();
  params.setBlockHash("00000");
  params.setNum(100);
  params.setTable("t_demo");

  request.setParams(params);
  String content = objectMapper.writeValueAsString(request);
  String result = dbService.process(content);

  MockResponse<InfoResponse> response =
      objectMapper.readValue(result, new TypeReference<MockResponse<InfoResponse>>() {});

  assertEquals(response.getCode(), new Integer(0));
  InfoResponse info = (InfoResponse) response.getResult();

  assertLinesMatch(info.getIndices(),
      Stream.of("field1", "field2", "field3").collect(Collectors.toList()));
}
 
Example #3
Source File: AccumulatingEntriesSpliteratorTest.java    From streams-utils with Apache License 2.0 6 votes vote down vote up
@Test
public void should_accumulate_an_entry_stream_into_the_correct_entry_stream() {
    // Given
    Stream<Map.Entry<Integer, String>> entries =
            Stream.of(
                    new AbstractMap.SimpleEntry<>(1, "1"),
                    new AbstractMap.SimpleEntry<>(2, "2"),
                    new AbstractMap.SimpleEntry<>(3, "3"),
                    new AbstractMap.SimpleEntry<>(4, "4")
            );

    // When
    Stream<Map.Entry<Integer, String>> accumulate = StreamsUtils.accumulateEntries(entries, String::concat);

    // Then
    assertThat(accumulate.collect(toList())).containsExactly(
            new AbstractMap.SimpleEntry<>(1, "1"),
            new AbstractMap.SimpleEntry<>(2, "12"),
            new AbstractMap.SimpleEntry<>(3, "123"),
            new AbstractMap.SimpleEntry<>(4, "1234")
    );
}
 
Example #4
Source File: ContainerProviderRule.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveParameter(final ParameterContext parameterContext, final ExtensionContext extensionContext)
        throws ParameterResolutionException {
    if (super.supports(parameterContext.getParameter().getType())) {
        return super.findInstance(extensionContext, parameterContext.getParameter().getType());
    }
    final DependenciesTxtBuilder builder = new DependenciesTxtBuilder();
    final String[] deps = parameterContext.getParameter().getAnnotation(Instance.class).value();
    Stream.of(deps).forEach(builder::withDependency);
    return manager
            .get()
            .builder(extensionContext.getRequiredTestClass().getName() + "."
                    + extensionContext.getRequiredTestMethod().getName() + "#" + manager.get().findAll().size(),
                    create(builder.build()).getAbsolutePath())
            .create();
}
 
Example #5
Source File: HistoricCaseInstanceInvolvementTest.java    From flowable-engine with Apache License 2.0 6 votes vote down vote up
@Test
public void getCaseInstanceWithTwoInvolvedGroups() {
    CaseInstance caseInstance = cmmnRuntimeService.createCaseInstanceBuilder()
            .caseDefinitionKey("oneTaskCase")
            .start();
    cmmnRuntimeService.addGroupIdentityLink(caseInstance.getId(), "testGroup", IdentityLinkType.PARTICIPANT);
    cmmnRuntimeService.addGroupIdentityLink(caseInstance.getId(), "testGroup2", IdentityLinkType.PARTICIPANT);

    assertThat(cmmnHistoryService.createHistoricCaseInstanceQuery().involvedGroups(
            Stream.of("testGroup", "testGroup2", "testGroup3").collect(Collectors.toSet())).count())
            .isEqualTo(1);
    assertThat(cmmnHistoryService.createHistoricCaseInstanceQuery().involvedGroups(
            Stream.of("testGroup", "testGroup2", "testGroup3").collect(Collectors.toSet())).list().get(0).getId()).isEqualTo(caseInstance.getId());
    assertThat(cmmnHistoryService.createHistoricCaseInstanceQuery().involvedGroups(
            Stream.of("testGroup", "testGroup2", "testGroup3").collect(Collectors.toSet())).singleResult().getId()).isEqualTo(caseInstance.getId());
}
 
Example #6
Source File: TestColumnIndexFiltering.java    From parquet-mr with Apache License 2.0 6 votes vote down vote up
private static void assertContains(Stream<User> expected, List<User> actual) {
  Iterator<User> expIt = expected.iterator();
  if (!expIt.hasNext()) {
    return;
  }
  User exp = expIt.next();
  for (User act : actual) {
    if (act.equals(exp)) {
      if (!expIt.hasNext()) {
        break;
      }
      exp = expIt.next();
    }
  }
  assertFalse("Not all expected elements are in the actual list. E.g.: " + exp, expIt.hasNext());
}
 
Example #7
Source File: ProjectAnalyzerTest.java    From jaxrs-analyzer with Apache License 2.0 6 votes vote down vote up
@Before
public void setUp() throws MalformedURLException {
    LogProvider.injectDebugLogger(System.out::println);

    final String testClassPath = "src/test/jaxrs-test";

    // invoke compilation for jaxrs-test classes
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    final List<JavaFileObject> compilationUnits = findClassFiles(testClassPath, fileManager);

    final JavaCompiler.CompilationTask compilationTask = compiler.getTask(null, null, null, singletonList("-g"), null, compilationUnits);
    assertTrue("Could not compile test project", compilationTask.call());

    path = Paths.get(testClassPath).toAbsolutePath();

    final Set<Path> classPaths = Stream.of(System.getProperty("java.class.path").split(File.pathSeparator))
            .map(Paths::get)
            .collect(Collectors.toSet());

    classPaths.add(path);
    classUnderTest = new ProjectAnalyzer(classPaths);
}
 
Example #8
Source File: FieldsAndGetters.java    From durian with Apache License 2.0 6 votes vote down vote up
/**
 * Returns a {@code Stream} of all public getter methods which match {@code predicate} and their return values for the given object.
 * <p>
 * This method uses reflection to find all of the public instance methods which don't take any arguments
 * and return a value.  If they pass the given predicate, then they are called, and the return value is
 * included in a stream of {@code Map.Entry<Method, Object>}.
 * <p>
 * Note that there are some methods which have the signature of a getter, but actually mutate the object
 * being inspected, e.g. {@link java.io.InputStream#read()}.  These will be called unless you manually
 * exclude them using the predicate.
 */
public static Stream<Map.Entry<Method, Object>> getters(Object obj, Predicate<Method> predicate) {
	Class<?> clazz = obj == null ? ObjectIsNull.class : obj.getClass();
	return Arrays.asList(clazz.getMethods()).stream()
			// we only want methods that don't take parameters
			.filter(method -> method.getParameterTypes().length == 0)
			// we only want public methods
			.filter(method -> Modifier.isPublic(method.getModifiers()))
			// we only want instance methods
			.filter(method -> !Modifier.isStatic(method.getModifiers()))
			// we only want methods that don't return void
			.filter(method -> !method.getReturnType().equals(Void.TYPE))
			// we only want methods that pass our predicate
			.filter(predicate)
			// turn it into Map<Method, Result>
			.map(method -> createEntry(method, tryCall(method.getName(), () -> method.invoke(obj))));
}
 
Example #9
Source File: JShellConfigRunner.java    From pro with GNU General Public License v3.0 6 votes vote down vote up
private static void run(Path configFile, PropertySequence propertySeq, List<String> arguments) {
  //System.out.println("run with jshell " + configFile);
  
  var args =
    Stream.of(
      Stream.of("-R-XX:+EnableValhalla").filter(__ -> System.getProperty("valhalla.enableValhalla") != null),
      Stream.of("-R--add-modules=ALL-SYSTEM"),  // also add incubator modules
      Stream.of("-R--enable-preview"),
      Stream.of("-R-Dpro.exitOnError=false"),
      propertySeq.stream().map(entry -> "-D" + entry.getKey() + '=' + entry.getValue()),
      Stream.of(arguments).filter(a -> !a.isEmpty()).map(a -> "-R-Dpro.arguments=" + String.join(",", a)),
      Stream.of(configFile.toString())
      )
    .flatMap(s -> s)
    .toArray(String[]::new);
  
  int exitCode = JShellWrapper.run(System.in, System.out, System.err, args);
  if (exitCode != 0) {
    System.err.println("error while executing jshell " + String.join(" ", args));
  }
  System.exit(exitCode);
}
 
Example #10
Source File: FlinkIntegrationIT.java    From rheem with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiSourceAndHoleAndMultiSink() throws URISyntaxException {
    // Define some input data.
    final List<String> collection1 = Arrays.asList("This is source 1.", "This is source 1, too.");
    final List<String> collection2 = Arrays.asList("This is source 2.", "This is source 2, too.");
    List<String> collector1 = new LinkedList<>();
    List<String> collector2 = new LinkedList<>();
    final RheemPlan rheemPlan = RheemPlans.multiSourceHoleMultiSink(collection1, collection2, collector1, collector2);


    makeAndRun(rheemPlan, FLINK);

    // Check the results in both sinks.
    List<String> expectedOutcome = Stream.concat(collection1.stream(), collection2.stream())
            .flatMap(string -> Arrays.asList(string.toLowerCase(), string.toUpperCase()).stream())
            .collect(Collectors.toList());
    Collections.sort(expectedOutcome);
    Collections.sort(collector1);
    Collections.sort(collector2);
    Assert.assertEquals(expectedOutcome, collector1);
    Assert.assertEquals(expectedOutcome, collector2);
}
 
Example #11
Source File: PageFetcherCurrentAndTotalPagesSplitIteratorTest.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Test
public void testSplitIterator() {
    PageFetcherCurrentAndTotalPagesSplitIterator<Integer> integerPageFetcherSplitIterator = new PageFetcherCurrentAndTotalPagesSplitIterator<>(pageToFetch -> {
        // return fake paginated result

        int startIdx = pageToFetch * 10;
        int endIdx = pageToFetch == 5 ? (pageToFetch + 1) * 10 - 5 : (pageToFetch + 1) * 10;

        List<Integer> collect = IntStream.range(startIdx, endIdx).boxed().collect(Collectors.toList());
        ListWithLastPage<Integer> list = new ListWithLastPage<>();
        list.setList(collect);
        list.setLastPage(5);
        return list;
    }, 0);

    Stream<Integer> stream = StreamSupport.stream(integerPageFetcherSplitIterator, false);

    assertEquals(
            IntStream.range(0, 55).boxed().collect(Collectors.toList()),
            stream.collect(Collectors.toList())
    );
}
 
Example #12
Source File: ClientSetup.java    From component-runtime with Apache License 2.0 6 votes vote down vote up
private ClientBuilder createClient(final ExecutorService executor, final Optional<String> keystoreLocation,
        final Optional<String> keystoreType, final String keystorePassword, final Optional<String> truststoreType,
        final List<String> serverHostnames) {
    final ClientBuilder builder = ClientBuilder.newBuilder();
    builder.connectTimeout(connectTimeout, MILLISECONDS);
    builder.readTimeout(readTimeout, MILLISECONDS);
    builder.executorService(executor);
    if (acceptAnyCertificate) {
        builder.hostnameVerifier((host, session) -> true);
        builder.sslContext(createUnsafeSSLContext());
    } else if (keystoreLocation.isPresent()) {
        builder.hostnameVerifier((host, session) -> serverHostnames.contains(host));
        builder.sslContext(createSSLContext(keystoreLocation, keystoreType, keystorePassword, truststoreType));
    }
    providers.map(it -> Stream.of(it.split(",")).map(String::trim).filter(v -> !v.isEmpty()).map(fqn -> {
        try {
            return Thread.currentThread().getContextClassLoader().loadClass(fqn).getConstructor().newInstance();
        } catch (final Exception e) {
            log.warn("Can't add provider " + fqn + ": " + e.getMessage(), e);
            return null;
        }
    }).filter(Objects::nonNull)).ifPresent(it -> it.forEach(builder::register));
    return ClientTracingRegistrar.configure(builder);
}
 
Example #13
Source File: MainPanel.java    From java-swing-tips with MIT License 5 votes vote down vote up
private MainPanel() {
  super(new GridLayout(3, 1));

  JTabbedPaneWithCloseButton tab1 = new JTabbedPaneWithCloseButton();
  JTabbedPaneWithCloseIcons tab2 = new JTabbedPaneWithCloseIcons();
  CloseableTabbedPane tab3 = new CloseableTabbedPane();

  Stream.of(tab1, tab2, tab3).map(MainPanel::makeTabbedPane).forEach(this::add);
  setPreferredSize(new Dimension(320, 240));
}
 
Example #14
Source File: GenModuleInfo.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private Set<String> packages(Path dir) {
    try (Stream<Path> stream = Files.find(dir, Integer.MAX_VALUE,
                         ((path, attrs) -> attrs.isRegularFile() &&
                                           path.toString().endsWith(".class")))) {
        return stream.map(path -> toPackageName(dir.relativize(path)))
                     .filter(pkg -> pkg.length() > 0)   // module-info
                     .distinct()
                     .collect(Collectors.toSet());
    } catch (IOException x) {
        throw new UncheckedIOException(x);
    }
}
 
Example #15
Source File: MutableIntTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Test
public void testMutate(){
	MutableInt num = MutableInt.of(20);

	Stream.of(1,2,3,4).map(i->i*10).peek(i-> num.mutate(n->n+i)).forEach(System.out::println);

	assertThat(num.getAsInt(),is(120));
}
 
Example #16
Source File: Fields.java    From ProjectAres with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Field one(Stream<Field> fields, Class<?> decl, TypeToken<?> type, String description) {
    final List<Field> list = fields.collect(Collectors.toList());
    switch(list.size()) {
        case 0: throw new NoSuchFieldError("No field " + description + " " + type +
                                           " in " + decl.getName());
        case 1: return list.get(0);
        default: throw new NoSuchFieldError("Multiple fields " + description + " " + type +
                                            " in " + decl.getName() +
                                            ": " + list.stream().map(Field::getName).collect(Collectors.joining(", ")));
    }
}
 
Example #17
Source File: MapStreamValuesToFutureOfCompletedValuesTest.java    From commercetools-sync-java with Apache License 2.0 5 votes vote down vote up
@Test
void multiple_StreamToListWithDiffTypeMappingDuplicates_ReturnsFutureOfListOfMappedValuesWithDuplicates() {
    final CompletableFuture<List<Integer>> future = mapValuesToFutureOfCompletedValues(
        Stream.of("john", "john"), element -> completedFuture(element.length()), toList());
    final List<Integer> result = future.join();
    assertThat(result).containsExactly(4, 4);
    assertThat(result).isExactlyInstanceOf(ArrayList.class);
}
 
Example #18
Source File: AopInterceptor.java    From hasor with Apache License 2.0 5 votes vote down vote up
private List<Class<? extends MethodInterceptor>> collectAnno(AnnotatedElement element) {
    Aop[] annoSet = element.getAnnotationsByType(Aop.class);
    if (annoSet == null) {
        annoSet = new Aop[0];
    }
    return Arrays.stream(annoSet).flatMap(//
            (Function<Aop, Stream<Class<? extends MethodInterceptor>>>) aop -> Arrays.stream(aop.value())//
    ).collect(Collectors.toList());
}
 
Example #19
Source File: MapStream.java    From Strata with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a stream of map entries whose elements are those of the first stream followed by those of the second
 * stream.
 *
 * @param a  the first stream of entries
 * @param b  the second stream of entries
 * @param <K>  the key type
 * @param <V>  the value type
 * @return the concatenation of the two input streams
 */
public static <K, V> MapStream<K, V> concat(
    MapStream<? extends K, ? extends V> a,
    MapStream<? extends K, ? extends V> b) {

  @SuppressWarnings("unchecked")
  MapStream<K, V> kvMapStream = new MapStream<>(Streams.concat(
      (Stream<? extends Map.Entry<K, V>>) a,
      (Stream<? extends Map.Entry<K, V>>) b));
  return kvMapStream;
}
 
Example #20
Source File: RelationExecutor.java    From grakn with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Set<Variable> requiredVars() {
    Set<Variable> relationPlayers = property.relationPlayers().stream()
            .flatMap(relationPlayer -> Stream.of(relationPlayer.getPlayer().var(), getRoleVar(relationPlayer)))
            .collect(Collectors.toSet());

    relationPlayers.add(var);

    return Collections.unmodifiableSet(relationPlayers);
}
 
Example #21
Source File: InfiniteStreamWithLimitOpTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "Stream.limit")
public void testUnorderedFinite(String description, UnaryOperator<Stream<Long>> fs) {
    // Range is [0, Long.MAX_VALUE), splits are SUBSIZED
    // Such a size will induce out of memory errors for incorrect
    // slice implementations
    withData(longs()).
            stream(s -> fs.apply(s.filter(i -> true).unordered().boxed())).
            resultAsserter(unorderedAsserter()).
            exercise();
}
 
Example #22
Source File: WebAcServiceTest.java    From trellis with Apache License 2.0 5 votes vote down vote up
@Test
void testUnauthenticatedUser() {
    when(mockRootResource.stream(eq(PreferAccessControl))).thenAnswer(inv -> Stream.of(
            rdf.createQuad(PreferAccessControl, authIRI5, ACL.accessTo, rootIRI),
            rdf.createQuad(PreferAccessControl, authIRI5, ACL.agentClass, ACL.AuthenticatedAgent),
            rdf.createQuad(PreferAccessControl, authIRI5, ACL.mode, ACL.Read),
            rdf.createQuad(PreferAccessControl, authIRI5, ACL.mode, ACL.Append)));
    when(mockSession.getAgent()).thenReturn(Trellis.AnonymousAgent);
    assertAll("Test unauthenticated user access",
            checkCannotRead(rootIRI),
            checkCannotWrite(rootIRI),
            checkCannotAppend(rootIRI),
            checkCannotControl(rootIRI));
}
 
Example #23
Source File: ParsedStrategyTest.java    From robozonky with Apache License 2.0 5 votes vote down vote up
@Test
void sellOffStarted() {
    final DefaultPortfolio portfolio = DefaultPortfolio.EMPTY;
    final DefaultValues values = new DefaultValues(portfolio);
    // activate default sell-off 3 months before the given date, which is already in the past
    values.setExitProperties(new ExitProperties(LocalDate.now()
        .plusMonths(2)));
    final ParsedStrategy strategy = new ParsedStrategy(values, Collections.emptyList());
    // no loan or participation should be bought; every investment should be sold
    final LoanImpl l = ParsedStrategyTest.mockLoan(1000);
    final LoanDescriptor ld = new LoanDescriptor(l);
    final ParticipationDescriptor pd = ParsedStrategyTest.mockParticipationDescriptor(l);
    final Investment i = MockInvestmentBuilder.fresh(l, 200)
        .build();
    final InvestmentDescriptor id = new InvestmentDescriptor(i, () -> l);
    assertSoftly(softly -> {
        softly.assertThat(strategy.isPurchasingEnabled())
            .isFalse();
        softly.assertThat(strategy.isInvestingEnabled())
            .isTrue();
        softly.assertThat(strategy.getApplicableLoans(Stream.of(ld), FOLIO))
            .isEmpty();
        softly.assertThat(strategy.getApplicableParticipations(Stream.of(pd), FOLIO))
            .isEmpty();
        softly.assertThat(strategy.getMatchingSellFilters(Stream.of(id), FOLIO))
            .containsOnly(id);
    });
}
 
Example #24
Source File: WithoutTagAggregationClause.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public <X, R> Map<Tags, Collection<R>> apply(Stream<X> x_stream, Function<? super X, Tags> x_tag_fn, Function<? super X, R> x_map_fn) {
    return x_stream
            .map(x -> SimpleMapEntry.create(x_tag_fn.apply(x), x_map_fn.apply(x)))
            .filter(entry -> tags.stream().allMatch(entry.getKey()::contains))
            .collect(Collectors.groupingBy(
                    entry -> key_(entry.getKey()),
                    Collectors.mapping(Map.Entry::getValue, Collectors.toCollection(() -> (Collection<R>)new ArrayList()))));
}
 
Example #25
Source File: MoreCollectorsTest.java    From mill with MIT License 5 votes vote down vote up
@Test
public void testCollectorIgnoringCustom2() {
    String veggies = Stream.of("", null, "", null, "Tomato",
            "Lettuce", null, "Onion", "Beet", "", null,
            "Turnip")
            .collect(
                    MoreCollectors.excluding(s -> s == null || s.length() == 0, Collectors.joining(", "))
            );
    assertEquals(
            "Tomato, Lettuce, Onion, Beet, Turnip",
            veggies
    );
}
 
Example #26
Source File: FileDiffParseTest.java    From cover-checker with Apache License 2.0 5 votes vote down vote up
@Test
public void parserSimpleTest() {

	String s = "diff --git a/src/main/java/com/naver/nid/push/token/service/TokenService.java b/src/main/java/com/naver/nid/push/token/service/TokenService.java\n" +
			"index cef524e..fab825e 100644\n" +
			"--- a/src/main/java/com/naver/nid/push/token/service/TokenService.java\n" +
			"+++ b/src/main/java/com/naver/nid/push/token/service/TokenService.java\n" +
			"@@ -109,4 +109,8 @@ private PushInfraInfo convertToPushInfraInfo(DeviceInfo deviceInfo) {\n" +
			" \t\tlogger.debug(\"device info transform {} -> {}\", deviceInfo, info);\n" +
			" \t\treturn info;\n" +
			" \t}\n" +
			"+\n" +
			"+\tpublic Mono<Integer> forTest() {\n" +
			"+\t\treturn Mono.just(100);\n" +
			"+\t}\n" +
			" }";

	FileDiffReader reader = new FileDiffReader(new BufferedReader(new StringReader(s)));
	Stream<Diff> parse = reader.parse();

	List<Diff> collect = parse.collect(Collectors.toList());
	logger.debug("{}", collect);

	assertEquals(1, collect.size());
	Diff diff = collect.get(0);
	assertEquals("src/main/java/com/naver/nid/push/token/service/TokenService.java", diff.getFileName());
	assertEquals(1, diff.getDiffSectionList().size());

	DiffSection diffSection = diff.getDiffSectionList().get(0);
	Line line = diffSection.getLineList().get(0);
	assertEquals(109, line.getLineNumber());
	assertEquals("\t\tlogger.debug(\"device info transform {} -> {}\", deviceInfo, info);", line.getBody());
}
 
Example #27
Source File: FlatMapOpTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testOps(String name, TestData.OfRef<Integer> data) {
    Collection<Integer> result = exerciseOps(data, s -> s.flatMap(mfId));
    assertEquals(data.size(), result.size());

    result = exerciseOps(data, s -> s.flatMap(mfNull));
    assertEquals(0, result.size());

    result = exerciseOps(data, s-> s.flatMap(e -> Stream.empty()));
    assertEquals(0, result.size());
}
 
Example #28
Source File: InteractionIdentifierTest.java    From baleen with Apache License 2.0 5 votes vote down vote up
@Test
public void testProcess() {
  // Note in this test we are using non-lemma versions of the words (hence jumps / jumped are
  // different)
  List<PatternReference> patterns =
      Arrays.asList(
          new PatternReference("1", new Word("jumps", POS.VERB)),
          new PatternReference("13", new Word("jumped", POS.VERB)),
          new PatternReference("2", new Word("springs", POS.VERB)),
          new PatternReference("3", new Word("leaps", POS.VERB)),
          new PatternReference("4", new Word("brother", POS.NOUN)),
          new PatternReference("11", new Word("brother", POS.NOUN), new Word("law", POS.NOUN)),
          new PatternReference(
              "12",
              new Word("step", POS.NOUN),
              new Word("brother", POS.NOUN),
              new Word("law", POS.NOUN)),
          new PatternReference("5", new Word("sister", POS.NOUN)),
          new PatternReference("6", new Word("sibling", POS.NOUN)),
          new PatternReference("7", new Word("sister", POS.NOUN), new Word("law", POS.NOUN)),
          new PatternReference("8", new Word("step", POS.NOUN), new Word("mother", POS.NOUN)),
          new PatternReference("9", new Word("mother", POS.NOUN)),
          new PatternReference(
              "10",
              new Word("was", POS.VERB),
              new Word("penalised", POS.VERB),
              new Word("extent", POS.NOUN),
              new Word("law", POS.NOUN)));

  Stream<InteractionWord> words = identifier.process(patterns);

  List<String> list = words.map(w -> w.getWord().getLemma()).collect(Collectors.toList());
  // Only mother, brother and law appear often enough to be consider interaction words
  assertTrue(list.contains("mother"));
  assertTrue(list.contains("law"));
  assertTrue(list.contains("brother"));
  assertEquals(3, list.size());
}
 
Example #29
Source File: Scores.java    From codenjoy with GNU General Public License v3.0 5 votes vote down vote up
private List<LocalDate> getDaysBetween(String from, String to) {
    LocalDate start = LocalDate.parse(from, DAY_FORMATTER);
    LocalDate end = LocalDate.parse(to, DAY_FORMATTER);
    return Stream.iterate(start, date -> date.plusDays(1))
            .limit(ChronoUnit.DAYS.between(start, end))
            .collect(Collectors.toList());
}
 
Example #30
Source File: ParentPath.java    From nifi with Apache License 2.0 5 votes vote down vote up
@Override
public Stream<FieldValue> evaluate(final RecordPathEvaluationContext context) {
    final Stream<FieldValue> stream;
    final RecordPathSegment parentPath = getParentPath();
    if (parentPath == null) {
        stream = Stream.of(context.getContextNode());
    } else {
        stream = parentPath.evaluate(context);
    }

    return Filters.presentValues(stream.map(fieldVal -> fieldVal.getParent()));
}