io.vavr.collection.List Java Examples

The following examples show how to use io.vavr.collection.List. 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: QuickSortTests.java    From java-datatable with Apache License 2.0 6 votes vote down vote up
@Test
public void testMultiQuickSort() {

    DataTable table = DataTableBuilder
            .create("NewTable")
            .withColumn(Integer.class, "IndexCol", List.of(1, 2, 3, 4, 5, 6, 7))
            .withColumn(Integer.class, "NumberCol", List.of(2, 3, 3, 4, 4, 5, 5))
            .withColumn(String.class, "StringCol", List.of("aa", "bb", "cc", "dd", "ee", "ff", "gg"))
            .build().get();

    SortItem sortOne = new SortItem("NumberCol", SortOrder.Ascending);
    SortItem sortTwo = new SortItem("StringCol", SortOrder.Descending);

    Try<DataView> view = table.quickSort(Stream.of(sortOne, sortTwo));

    assertTrue(view.isSuccess());

    // Check Index Column values are as expected.
    assertTrue(view.get().row(0).getAs(Integer.class, "IndexCol") == 1);
    assertTrue(view.get().row(1).getAs(Integer.class, "IndexCol") == 3);
    assertTrue(view.get().row(2).getAs(Integer.class, "IndexCol") == 2);
    assertTrue(view.get().row(3).getAs(Integer.class, "IndexCol") == 5);
    assertTrue(view.get().row(4).getAs(Integer.class, "IndexCol") == 4);
    assertTrue(view.get().row(5).getAs(Integer.class, "IndexCol") == 7);
    assertTrue(view.get().row(6).getAs(Integer.class, "IndexCol") == 6);
}
 
Example #2
Source File: AriEventProcessing.java    From ari-proxy with GNU Affero General Public License v3.0 6 votes vote down vote up
public static Seq<MetricsGatherer> determineMetricsGatherer(AriMessageType type) {

		List<MetricsGatherer> metricsGatherers = List.of(callContextSupplier -> new IncreaseCounter(type.name()));

		switch (type) {
			case STASIS_START:
				metricsGatherers = metricsGatherers.appendAll(List.of(
						callContextSupplier -> new IncreaseCounter("CallsStarted"),
						callContextSupplier -> new StartCallSetupTimer(callContextSupplier.get())
				));
				break;
			case STASIS_END:
				metricsGatherers = metricsGatherers.append(
						callContextSupplier -> new IncreaseCounter("CallsEnded")
				);
				break;
		}

		return metricsGatherers;
	}
 
Example #3
Source File: CollectionAPIUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenList_whenPrependTail_thenCorrect() {
    List<Integer> intList = List.of(1, 2, 3);

    List<Integer> newList = intList.tail()
      .prepend(0);

    assertEquals(new Integer(1), intList.get(0));
    assertEquals(new Integer(2), intList.get(1));
    assertEquals(new Integer(3), intList.get(2));

    assertNotSame(intList.get(0), newList.get(0));
    assertEquals(new Integer(0), newList.get(0));
    assertSame(intList.get(1), newList.get(1));
    assertSame(intList.get(2), newList.get(2));
}
 
Example #4
Source File: SerializationFeatureTest.java    From vavr-jackson with Apache License 2.0 6 votes vote down vote up
@Test
public void vavr_List_DateTime_serialization_should_use_SerializationFeature() throws IOException {
    final DateTime dateTime = new DateTime(2016, 6, 6, 8, 0, DateTimeZone.forID("CET"));
    final io.vavr.collection.List<DateTime> dateTimeList = List.of(dateTime);
    final java.util.List<DateTime> dateTimeJavaList = new ArrayList<>();
    dateTimeJavaList.add(dateTime);

    final CsvMapper mapper = getMapper();
    final ObjectWriter writer = mapper.writer()
            .without(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    final String serializedDateTime = writer
            .writeValueAsString(dateTime);
    final String serializedDateTimeJavaList = writer
            .writeValueAsString(dateTimeJavaList);
    final String serializedDateTimeList = writer
            .writeValueAsString(dateTimeList);

    Assertions.assertEquals(serializedDateTime, serializedDateTimeJavaList);
    Assertions.assertEquals(serializedDateTimeJavaList, serializedDateTimeList);

    List<DateTime> restored = mapper.readValue(serializedDateTimeList, new TypeReference<List<DateTime>>() {});
    Assertions.assertEquals(restored.head().getMillis(), dateTime.getMillis());

}
 
Example #5
Source File: CollectionAPIUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenMap_whenMapApi_thenCorrect() {
    Map<Integer, List<Integer>> map = List.rangeClosed(0, 10)
      .groupBy(i -> i % 2);
    
    assertEquals(2, map.size());
    assertEquals(6, map.get(0).get().size());
    assertEquals(5, map.get(1).get().size());

    Map<String, String> map1
      = HashMap.of("key1", "val1", "key2", "val2", "key3", "val3");

    Map<String, String> fMap
      = map1.filterKeys(k -> k.contains("1") || k.contains("2"));
    assertFalse(fMap.containsKey("key3"));

    Map<String, String> fMap2
      = map1.filterValues(v -> v.contains("3"));
    assertEquals(fMap2.size(), 1);
    assertTrue(fMap2.containsValue("val3"));

    Map<String, Integer> map2 = map1.map(
      (k, v) -> Tuple.of(k, Integer.valueOf(v.charAt(v.length() - 1) + "") ));
    assertEquals(map2.get("key1").get().intValue(), 1);
}
 
Example #6
Source File: CollectionAPIUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@Test
public void givenStream_whenProcessed_thenCorrect() {

    Stream<Integer> s1 = Stream.tabulate(5, (i)-> i + 1);
    assertEquals(s1.get(2).intValue(), 3);

    Stream<Integer> s = Stream.of(2,1,3,4);

    Stream<Tuple2<Integer, Integer>> s2 = s.zip(List.of(7,8,9));
    Tuple2<Integer, Integer> t1 = s2.get(0);
    assertEquals(t1._1().intValue(), 2);
    assertEquals(t1._2().intValue(), 7);

    Stream<Integer> intStream = Stream.iterate(0, i -> i + 1)
      .take(10);

    assertEquals(10, intStream.size());

    long evenSum = intStream.filter(i -> i % 2 == 0)
      .sum()
      .longValue();

    assertEquals(20, evenSum);
}
 
Example #7
Source File: Kanela.java    From kanela with Apache License 2.0 6 votes vote down vote up
/**
 * Removes all instrumentation modules already applied by Kanela and re-scans the instrumentation class path for
 * modules to apply them on the current JVM.
 */
public static void reload(boolean clearRegistry) {

  // We will only proceed to reload if Kanela was properly started already.
  if(Kanela.instrumentation != null) {
      if(clearRegistry)
        InstrumentationRegistryListener.instance().clear();

      InstrumentationClassPath.build().use(instrumentationClassLoader -> {
          installedTransformers.forEach(transformer -> instrumentation.removeTransformer(transformer.getClassFileTransformer()));
          installedTransformers = List.empty();

          val configuration = KanelaConfiguration.from(instrumentationClassLoader);
          Logger.configureLogger(configuration);
          installedTransformers = InstrumentationLoader.load(instrumentation, instrumentationClassLoader, configuration);
      });
  }
}
 
Example #8
Source File: IntervalFunctionTest.java    From resilience4j with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldPassPositiveDuration() {
    final List<Long> positiveIntervals = List.of(10L, 99L, 981L);
    final List<Duration> positiveDurations = positiveIntervals.map(Duration::ofMillis);

    positiveDurations.forEach(IntervalFunction::of);
    positiveIntervals.forEach(IntervalFunction::of);
    positiveDurations.forEach(IntervalFunction::ofRandomized);
    positiveIntervals.forEach(IntervalFunction::ofRandomized);
    positiveDurations.forEach(IntervalFunction::ofExponentialBackoff);
    positiveIntervals.forEach(IntervalFunction::ofExponentialBackoff);
    positiveDurations.forEach(IntervalFunction::ofExponentialRandomBackoff);
    positiveIntervals.forEach(IntervalFunction::ofExponentialRandomBackoff);

    assertThat(true).isTrue();
}
 
Example #9
Source File: BeanTest.java    From vavr-jackson with Apache License 2.0 6 votes vote down vote up
@Test
void test2() throws IOException {
    ComplexInnerClass innerSrc = new ComplexInnerClass();
    innerSrc.setScalar(10);
    innerSrc.setValues(List.of("Data1", "Data2", "Data3"));

    ComplexBeanObject src = new ComplexBeanObject();
    src.setScalar("Data Scalar");
    src.setValues(List.of(
            new ComplexInnerClass(10, List.of("Data1", "Data2", "Data3")),
            new ComplexInnerClass(12, List.of("Data3", "Data4", "Data5"))
    ));

    String json = mapper().writeValueAsString(src);

    ComplexBeanObject restored = mapper().readValue(json, ComplexBeanObject.class);
    restored.getValues().forEach(innerClass -> {
        Assertions.assertTrue(innerClass instanceof ComplexInnerClass, "Instance of ComplexInnerClass");
    });

    Assertions.assertEquals(restored, src);
}
 
Example #10
Source File: CollectionAPIUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test(expected = UnsupportedOperationException.class)
public void givenVavrList_whenConvertedView_thenException() {
    java.util.List<Integer> javaList = List.of(1, 2, 3)
      .asJava();

    assertEquals(3, javaList.get(2).intValue());
    javaList.add(4);
}
 
Example #11
Source File: ParameterizedPojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testListOfTuple() throws Exception {
    String src00 = "A";
    String src01 = "B";
    Tuple2<String, String> src0 = Tuple.of(src00, src01);
    List<Tuple2<String, String>> src = List.of(src0);
    String json = MAPPER.writeValueAsString(new ParameterizedListPojo<>(src));
    Assertions.assertEquals(json, "{\"value\":[[\"A\",\"B\"]]}");
    ParameterizedListPojo<io.vavr.Tuple2<java.lang.String, java.lang.String>> restored =
            MAPPER.readValue(json, new TypeReference<ParameterizedListPojo<io.vavr.Tuple2<java.lang.String, java.lang.String>>>(){});
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #12
Source File: SeqTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testWithOption() throws Exception {
    verifySerialization(typeReferenceWithOption(), List.of(
            Tuple.of(of(Option.some("value")), genJsonList("value")),
            Tuple.of(of(Option.none()), genJsonList((Object) null))
    ));
}
 
Example #13
Source File: TupleTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
private String genJsonTuple(Object head, Object tail) {
    java.util.List<Object> map = new ArrayList<>();
    for (int i = 0; i < arity(); i++) {
        map.add(i == 0 ? head : tail);
    }
    return genJsonList(map.toArray());
}
 
Example #14
Source File: IntervalFunctionTest.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldRejectOutOfBoundsMultiplier() {
    final Duration duration = Duration.ofMillis(100);
    final float lessThenOneMultiplier = 0.9999f;

    final List<Try> tries = List.of(
        Try.of(() -> IntervalFunction.ofExponentialBackoff(duration, lessThenOneMultiplier)),
        Try.of(
            () -> IntervalFunction.ofExponentialRandomBackoff(duration, lessThenOneMultiplier))
    );

    assertThat(tries.forAll(Try::isFailure)).isTrue();
    assertThat(tries.map(Try::getCause).forAll(t -> t instanceof IllegalArgumentException))
        .isTrue();
}
 
Example #15
Source File: DataTableTests.java    From java-datatable with Apache License 2.0 5 votes vote down vote up
@Test
public void testColumnLengthMismatch() {
    List<String> dataOne = List.of("AA", "BB", "CC", "DD");
    IDataColumn colOne = new DataColumn<>(String.class, "StringCol", dataOne);

    List<String> dataTwo = List.of("XX", "YY", "ZZ");
    IDataColumn colTwo = new DataColumn<>(String.class, "StringColTwo", dataTwo);

    IDataColumn[] cols = { colOne, colTwo };
    Try<DataTable> table = DataTable.build("NewTable", cols);

    assertTrue(table.isFailure());
    assertEquals(table.getCause().getMessage(), "Columns have different lengths.");
}
 
Example #16
Source File: CircuitBreakerEventsEndpoint.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
private List<CircuitBreakerEvent> getCircuitBreakerEvents(String circuitBreakerName) {
    CircularEventConsumer<CircuitBreakerEvent> eventConsumer = eventConsumerRegistry
        .getEventConsumer(circuitBreakerName);
    if (eventConsumer != null) {
        return eventConsumer.getBufferedEvents()
            .filter(event -> event.getCircuitBreakerName().equals(circuitBreakerName));
    } else {
        return List.empty();
    }
}
 
Example #17
Source File: ParameterizedPojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testListOfString() throws Exception {
    String src0 = "A";
    String src1 = "B";
    String src2 = "C";
    List<String> src = List.of(src0, src1, src2);
    String json = MAPPER.writeValueAsString(new ParameterizedListPojo<>(src));
    Assertions.assertEquals(json, "{\"value\":[\"A\",\"B\",\"C\"]}");
    ParameterizedListPojo<java.lang.String> restored =
            MAPPER.readValue(json, new TypeReference<ParameterizedListPojo<java.lang.String>>(){});
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #18
Source File: VavrUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenCreatesVavrList_thenCorrect() {
    List<Integer> intList = List.of(1, 2, 3);
    assertEquals(3, intList.length());
    assertEquals(new Integer(1), intList.get(0));
    assertEquals(new Integer(2), intList.get(1));
    assertEquals(new Integer(3), intList.get(2));
}
 
Example #19
Source File: PlacingOnHoldPolicy.java    From library with MIT License 5 votes vote down vote up
static List<PlacingOnHoldPolicy> allCurrentPolicies() {
    return List.of(
            onlyResearcherPatronsCanHoldRestrictedBooksPolicy,
            overdueCheckoutsRejectionPolicy,
            regularPatronMaximumNumberOfHoldsPolicy,
            onlyResearcherPatronsCanPlaceOpenEndedHolds);
}
 
Example #20
Source File: BulkheadEventsEndpoint.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
@ReadOperation
public BulkheadEventsEndpointResponse getAllBulkheadEvents() {
    java.util.List<BulkheadEventDTO> response = eventConsumerRegistry.getAllEventConsumer()
        .flatMap(CircularEventConsumer::getBufferedEvents)
        .sorted(Comparator.comparing(BulkheadEvent::getCreationTime))
        .map(BulkheadEventDTOFactory::createBulkheadEventDTO)
        .toJavaList();

    return new BulkheadEventsEndpointResponse(response);
}
 
Example #21
Source File: EitherTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testWithOption() throws IOException {
    TypeReference<Either<Option<String>, Option<String>>> typeReference = new TypeReference<Either<Option<String>, Option<String>>>() {};
    verifySerialization(typeReference, List.of(
            Tuple.of(Either.left(none()), genJsonList("left", null)),
            Tuple.of(Either.right(none()), genJsonList("right", null)),
            Tuple.of(Either.left(some("value")), genJsonList("left", "value")),
            Tuple.of(Either.right(some("value")), genJsonList("right", "value"))
    ));
}
 
Example #22
Source File: CollectionAPIUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenVavrList_whenConverted_thenCorrect() {
    Integer[] array = List.of(1, 2, 3)
      .toJavaArray(Integer.class);
    assertEquals(3, array.length);

    java.util.Map<String, Integer> map = List.of("1", "2", "3")
      .toJavaMap(i -> Tuple.of(i, Integer.valueOf(i)));
    assertEquals(2, map.get("2").intValue());
}
 
Example #23
Source File: GuardTests.java    From java-datatable with Apache License 2.0 5 votes vote down vote up
@Test
public void testIterableValidArgument() {
    try{
        List<String> myList = List.of("a", "b", "c");
        Guard.itemsNotNull(myList, "ArgumentOne");
    }
    catch(Exception e){
        fail("Should not have thrown any exception");
    }
}
 
Example #24
Source File: Issue154Test.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void itShouldSerializeJavaListWithoutModule() throws Exception {
    MyJavaClass myClass = new MyJavaClass();
    myClass.dates = List.of(new Date(1591221600000L), new Date(1591308000000L)).asJava();

    ObjectMapper mapper = new ObjectMapper();

    String json = mapper.writeValueAsString(myClass);
    assertEquals("{\"dates\":[\"2020-06-04\",\"2020-06-05\"]}", json);
}
 
Example #25
Source File: W3CShaclTestSuite.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
private Resource findManifestResource() {

            java.util.List<Statement> manifestTypeStmts =
                    getModel().listStatements(null, RDF.type, DATA_ACCESS_TESTS.Manifest).toList();

            if(manifestTypeStmts.size() != 1) {
                throw new RuntimeException("no Manifest resource or ambiguity due to several Manifests");
            }

            return manifestTypeStmts.get(0).getSubject();
        }
 
Example #26
Source File: W3CShaclTest.java    From RDFUnit with Apache License 2.0 5 votes vote down vote up
@Ignore
@Test
public void runW3CTests() {
    val rootManifestPath = Paths.get("tests/manifest.ttl");

    val suite = W3CShaclTestSuite.load(rootManifestPath, false);

    //suite.getTestCases().parallelStream().forEach(TestCase::getExecution);
    val failureCount = suite.getTestCases().stream().filter(t -> t.getExecution().isFailure()).count();

    val hist = List.ofAll(suite.getTestCases()).groupBy(W3CShaclTestSuite.TestCase::getEarlOutcome).mapValues(Traversable::size);

    System.out.println(hist);
}
 
Example #27
Source File: SimplePojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testListOfTuple() throws Exception {
    String src00 = "A";
    String src01 = "B";
    Tuple2<String, String> src0 = Tuple.of(src00, src01);
    List<Tuple2<String, String>> src = List.of(src0);
    String json = MAPPER.writeValueAsString(new ListOfTuple().setValue(src));
    Assertions.assertEquals(json, "{\"value\":[[\"A\",\"B\"]]}");
    ListOfTuple restored = MAPPER.readValue(json, ListOfTuple.class);
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #28
Source File: CollectionsInteroperabilityUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenParams_whenVavrListConvertedToMutable_thenRetunMutableList() {
  java.util.List<String> javaList = List.of("Java", "Haskell", "Scala")
    .asJavaMutable();
  javaList.add("Python");
  assertEquals(4, javaList.size());
}
 
Example #29
Source File: AnalyzedClass.java    From kanela with Apache License 2.0 5 votes vote down vote up
private Predicate<Boolean> buildClassRefinerPredicate(ClassRefiner classRefiner) {
    java.util.List<Predicate<Boolean>> allPredicates = Arrays.asList(
            p -> containsFields(classRefiner.getFields()),
            p -> containsMethodWithParameters(classRefiner.getMethods())
    );
    return allPredicates.stream().reduce(p -> true, Predicate::and);
}
 
Example #30
Source File: CollectionAPIUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenVavrList_whenCollected_thenCorrect() {
    java.util.Set<Integer> javaSet = List.of(1, 2, 3)
      .collect(Collectors.toSet());

    assertEquals(3, javaSet.size());
    assertEquals(1, javaSet.toArray()[0]);
}