io.vavr.collection.HashMap Java Examples

The following examples show how to use io.vavr.collection.HashMap. 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: 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 #2
Source File: CQLStoreManager.java    From grakn with GNU Affero General Public License v3.0 6 votes vote down vote up
private void initialiseKeyspace() {
    // if the keyspace already exists, just return
    if (this.session.getMetadata().getKeyspace(this.keyspace).isPresent()) {
        return;
    }

    Configuration configuration = getStorageConfig();

    // Setting replication strategy based on value reading from the configuration: either "SimpleStrategy" or "NetworkTopologyStrategy"
    Map<String, Object> replication = Match(configuration.get(REPLICATION_STRATEGY)).of(
            Case($("SimpleStrategy"), strategy -> HashMap.<String, Object>of("class", strategy, "replication_factor", configuration.get(REPLICATION_FACTOR))),
            Case($("NetworkTopologyStrategy"),
                    strategy -> HashMap.<String, Object>of("class", strategy)
                            .merge(Array.of(configuration.get(REPLICATION_OPTIONS))
                                    .grouped(2)
                                    .toMap(array -> Tuple.of(array.get(0), Integer.parseInt(array.get(1)))))))
            .toJavaMap();

    session.execute(createKeyspace(this.keyspace)
            .ifNotExists()
            .withReplicationOptions(replication)
            .build());
}
 
Example #3
Source File: MapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
void testJaxbXmlSerialization() throws IOException {
    java.util.Map<String, String> javaInit = new java.util.HashMap<>();
    javaInit.put("key1", "1");
    javaInit.put("key2", "2");
    Map<String, String> slangInit = this.<String, String>emptyMap().put("key1", "1").put("key2", "2");
    ObjectMapper mapper = xmlMapperJaxb();
    String javaJson = mapper.writeValueAsString(new JaxbXmlSerializeJavaUtil().init(javaInit));
    String slangJson = mapper.writeValueAsString(new JaxbXmlSerializeVavr().init(slangInit));
    Assertions.assertEquals(javaJson, slangJson);
    JaxbXmlSerializeVavr restored = mapper.readValue(slangJson, JaxbXmlSerializeVavr.class);
    Assertions.assertEquals(restored.transitTypes.get("key1").get(), "1");
    Assertions.assertEquals(restored.transitTypes.get("key2").get(), "2");
}
 
Example #4
Source File: ReplicationIntegrationSpec.java    From ts-reaktive with MIT License 5 votes vote down vote up
public DC(final String name, final int httpPort, Map<String,Integer> remotes) {
    this.name = name;
    config = ConfigFactory.parseMap(HashMap.<String,Object>
        of("clustering.port", clusteringPort)
        .put("clustering.seed-port", clusteringPort)
        .put("ts-reaktive.replication.local-datacenter.name", name)
        .put("ts-reaktive.replication.server.host", "localhost")
        .put("ts-reaktive.replication.server.port", httpPort)
        .put("ts-reaktive.replication.cassandra.keyspace", "replication_" + name)
        .put("cassandra-journal.port", CassandraLauncher.randomPort())
        .put("clustering.name", name)
        .put("cassandra-journal.keyspace", name) // each datacenter is in its own cassandra keyspace
        .merge(
            HashMap.ofEntries(remotes.map(r -> Tuple.of("ts-reaktive.replication.remote-datacenters." + r._1 + ".url", "wss://localhost:" + r._2)))
        )
        .toJavaMap()
        ).withFallback(ConfigFactory.parseResources("com/tradeshift/reaktive/replication/ReplicationIntegrationSpec.conf")).withFallback(ConfigFactory.defaultReference()).resolve();
    
    system = ActorSystem.create(config.getString("clustering.name"), config);
    shardRegion = ReplicatedTestActor.sharding.shardRegion(system);
    
    new AkkaPersistence(system).awaitPersistenceInit();
    
    try {
        System.out.println("*** AWAITING (" + name + ")");
        Replication.get(system).start(HashMap.of(TestEvent.class, shardRegion)).toCompletableFuture().get(30, TimeUnit.SECONDS);
        System.out.println("*** DONE (" + name + ")");
    } catch (InterruptedException | ExecutionException | TimeoutException e) {
        throw new RuntimeException(e);
    }
    
}
 
Example #5
Source File: MapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
void testXmlSerialization() throws IOException {
    java.util.Map<String, String> javaInit = new java.util.HashMap<>();
    javaInit.put("key1", "1");
    javaInit.put("key2", "2");
    Map<String, String> slangInit = this.<String, String>emptyMap().put("key1", "1").put("key2", "2");
    ObjectMapper mapper = xmlMapper();
    String javaJson = mapper.writeValueAsString(new XmlSerializeJavaUtil().init(javaInit));
    String slangJson = mapper.writeValueAsString(new XmlSerializeVavr().init(slangInit));
    Assertions.assertEquals(javaJson, slangJson);
    XmlSerializeVavr restored = mapper.readValue(slangJson, XmlSerializeVavr.class);
    Assertions.assertEquals(restored.transitTypes.get("key1").get(), "1");
    Assertions.assertEquals(restored.transitTypes.get("key2").get(), "2");
}
 
Example #6
Source File: SimplePojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testHashMapOfString() throws Exception {
    Integer src00 = 1;
    String src01 = "A";
    Tuple2<Integer, String> src0 = Tuple.of(src00, src01);
    HashMap<Integer, String> src = HashMap.ofEntries(src0);
    String json = MAPPER.writeValueAsString(new HashMapOfString().setValue(src));
    Assertions.assertEquals(json, "{\"value\":{\"1\":\"A\"}}");
    HashMapOfString restored = MAPPER.readValue(json, HashMapOfString.class);
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #7
Source File: PolymorphicPojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testHashMap() throws Exception {
    HashMap<String, I> src = HashMap.of("a", new A(), "b", new B());
    String json = MAPPER.writeValueAsString(new HashMapPojo().setValue(src));
    Assertions.assertEquals(json, "{\"value\":{\"a\":{\"type\":\"a\"},\"b\":{\"type\":\"b\"}}}");
    HashMapPojo pojo = MAPPER.readValue(json, HashMapPojo.class);
    HashMap<String, I> restored = pojo.getValue();
    Assertions.assertTrue(restored.get("a").get() instanceof A);
    Assertions.assertTrue(restored.get("b").get() instanceof B);
}
 
Example #8
Source File: MultimapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testWithOption() throws Exception {
    Multimap<String, Option<Integer>> multimap = this.<String, Option<Integer>>emptyMap().put("1", Option.some(1)).put("1", Option.none());
    String json = genJsonMap(HashMap.of("1", asList(1, null)).toJavaMap());

    verifySerialization(typeReferenceWithOption(), io.vavr.collection.List.of(Tuple.of(multimap, json)));
}
 
Example #9
Source File: HeteroDescribableConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@SuppressWarnings("unused")
public Map<String, Class<T>> getImplementors() {
    return getDescriptors()
            .map(descriptor -> Tuple.of(preferredSymbol(descriptor), descriptor))
            .foldLeft(HashMap.empty(), this::handleDuplicateSymbols)
            .mapValues(this::descriptorClass)
            .toJavaMap();
}
 
Example #10
Source File: GithubRoutesConfig.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean
RouterFunction<ServerResponse> githubRoutes(final GithubProperties props,
                                            final WebClient githubWebClient) {
  return

      route(GET("/github/props/manual"),
            request -> ok().body(Mono.just(
                singletonMap("github",
                             singletonMap("token", props.getToken()))),
                                 Map.class))

          .andRoute(GET("/github/props/**"),
                    request -> ok().body(Mono.just(props), GithubProperties.class))

          .andRoute(GET("/github/search/users/{username}"), // ?page=1&size=2
                    request -> ok().body(githubWebClient.get()
                                                        .uri(
                                                            "/search/users?q={q}&page={page}&per_page={per_page}",
                                                            HashMap.of(
                                                                "q", request.pathVariable("username"),
                                                                "page", request.queryParam("page").orElse("0"),
                                                                "per_page", request.queryParam("size").orElse("3")
                                                            ).toJavaMap()
                                                        )
                                                        .exchange()
                                                        .subscribeOn(Schedulers.elastic())
                                                        .flatMapMany(response -> response.bodyToFlux(Map.class)),
                                         Map.class))

          .andRoute(GET("/**"),
                    request -> ok().body(Mono.just(singletonMap("result", "TODO")),
                                         Map.class))
      ;
}
 
Example #11
Source File: App.java    From spring-5-examples with MIT License 5 votes vote down vote up
@Bean
InitializingBean initDB() {
  return () -> HashMap.of(123, "ololo",
                          456, "trololo")
                      .map((orderNumber, description) -> Tuple.of(BigDecimal.valueOf(orderNumber * System.currentTimeMillis() / 1234567890.987654321),
                                                                  singletonList(description)))
                      .map(t -> Order.of(OrderNumber.of(t._1().intValue()), Price.of(t._1())))
                      .forEach(orderRepository::save);
}
 
Example #12
Source File: InMemoryRateLimiterRegistry.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
public InMemoryRateLimiterRegistry(Map<String, RateLimiterConfig> configs,
                                      List<RegistryEventConsumer<RateLimiter>> registryEventConsumers,
                                      io.vavr.collection.Map<String, String> tags, RegistryStore<RateLimiter> registryStore) {
    super(configs.getOrDefault(DEFAULT_CONFIG, RateLimiterConfig.ofDefaults()),
        registryEventConsumers, Optional.ofNullable(tags).orElse(HashMap.empty()),
        Optional.ofNullable(registryStore).orElse(new InMemoryRegistryStore<>()));
    this.configurations.putAll(configs);
}
 
Example #13
Source File: InMemoryBulkheadRegistry.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
public InMemoryBulkheadRegistry(Map<String, BulkheadConfig> configs,
                                      List<RegistryEventConsumer<Bulkhead>> registryEventConsumers,
                                      io.vavr.collection.Map<String, String> tags, RegistryStore<Bulkhead> registryStore) {
    super(configs.getOrDefault(DEFAULT_CONFIG, BulkheadConfig.ofDefaults()),
        registryEventConsumers, Optional.ofNullable(tags).orElse(HashMap.empty()),
        Optional.ofNullable(registryStore).orElse(new InMemoryRegistryStore<>()));
    this.configurations.putAll(configs);
}
 
Example #14
Source File: HeteroDescribableConfigurator.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
private Option<Descriptor<T>> lookupDescriptor(String symbol, CNode config) {
    return getDescriptors()
            .filter(descriptor -> findByPreferredSymbol(descriptor, symbol) || findBySymbols(descriptor, symbol, config))
            .map(descriptor -> Tuple.of(preferredSymbol(descriptor), descriptor))
            .foldLeft(HashMap.empty(), this::handleDuplicateSymbols)
            .values()
            .headOption()
            .orElse(() -> {
                throw new IllegalArgumentException("No " + target.getName() + " implementation found for " + symbol);
            });
}
 
Example #15
Source File: BindingClassTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testHashMapClass() throws Exception {
    HashMapClass src = new HashMapClass(HashMap.of(42, new ImplementedClass()));
    String json = MAPPER.writeValueAsString(src);
    HashMapClass restored = MAPPER.readValue(json, HashMapClass.class);
    Assertions.assertEquals(restored.value.head()._2.getClass(), ImplementedClass.class);
}
 
Example #16
Source File: SecurityUtil.java    From streaming-file-server with MIT License 5 votes vote down vote up
public static Map<String, String> displayName() {
  return HashMap.of(profileUrlKey, profileUrlValue,
                    displayName, Option.of(SecurityContextHolder.getContext())
                                       .map(SecurityContext::getAuthentication)
                                       .map(auth -> (auth instanceof UserDetails)
                                           ? ((UserDetails) auth).getUsername()
                                           : auth.getName())
                                       .getOrElse(() -> anonymousFriendlyName))
                .toJavaMap();
}
 
Example #17
Source File: MapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void test1() throws IOException {
    Map<Object, Object> vavrObject = emptyMap().put("1", 2);
    java.util.Map<Object, Object> javaObject = new java.util.HashMap<>();
    javaObject.put("1", 2);

    String json = mapper().writer().writeValueAsString(vavrObject);
    Assertions.assertEquals(genJsonMap(javaObject), json);

    Map<?, ?> restored = (Map<?, ?>) mapper().readValue(json, clz());
    Assertions.assertEquals(restored, vavrObject);
}
 
Example #18
Source File: InMemoryRetryRegistry.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
public InMemoryRetryRegistry(Map<String, RetryConfig> configs,
                                      List<RegistryEventConsumer<Retry>> registryEventConsumers,
                                      io.vavr.collection.Map<String, String> tags, RegistryStore<Retry> registryStore) {
    super(configs.getOrDefault(DEFAULT_CONFIG, RetryConfig.ofDefaults()),
        registryEventConsumers, Optional.ofNullable(tags).orElse(HashMap.empty()),
        Optional.ofNullable(registryStore).orElse(new InMemoryRegistryStore<>()));
    this.configurations.putAll(configs);
}
 
Example #19
Source File: TimeLimiterConfiguration.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
/**
 * Initializes a timeLimiter registry.
 *
 * @param timeLimiterConfigurationProperties The timeLimiter configuration properties.
 * @return a timeLimiterRegistry
 */
private static TimeLimiterRegistry createTimeLimiterRegistry(
    TimeLimiterConfigurationProperties timeLimiterConfigurationProperties,
    RegistryEventConsumer<TimeLimiter> timeLimiterRegistryEventConsumer,
    CompositeCustomizer<TimeLimiterConfigCustomizer> compositeTimeLimiterCustomizer) {

    Map<String, TimeLimiterConfig> configs = timeLimiterConfigurationProperties.getConfigs()
            .entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
                    entry -> timeLimiterConfigurationProperties.createTimeLimiterConfig(
                        entry.getKey(), entry.getValue(), compositeTimeLimiterCustomizer)));

    return TimeLimiterRegistry.of(configs, timeLimiterRegistryEventConsumer,
        HashMap.ofAll(timeLimiterConfigurationProperties.getTags()));
}
 
Example #20
Source File: InMemoryThreadPoolBulkheadRegistry.java    From resilience4j with Apache License 2.0 5 votes vote down vote up
public InMemoryThreadPoolBulkheadRegistry(Map<String, ThreadPoolBulkheadConfig> configs,
                                      List<RegistryEventConsumer<ThreadPoolBulkhead>> registryEventConsumers,
                                      io.vavr.collection.Map<String, String> tags, RegistryStore<ThreadPoolBulkhead> registryStore) {
    super(configs.getOrDefault(DEFAULT_CONFIG, ThreadPoolBulkheadConfig.ofDefaults()),
        registryEventConsumers, Optional.ofNullable(tags).orElse(HashMap.empty()),
        Optional.ofNullable(registryStore).orElse(new InMemoryRegistryStore<>()));
    this.configurations.putAll(configs);
}
 
Example #21
Source File: BindingClass.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    java.util.Map<Class<?>, Tuple2<String, String>> cases1 = new java.util.HashMap<>();
    cases1.put(List.class, Tuple.of("List.of(new ImplementedClass())", "head()"));
    cases1.put(HashSet.class, Tuple.of("HashSet.of(new ImplementedClass())", "head()"));
    cases1.put(Option.class, Tuple.of("Option.of(new ImplementedClass())", "get()"));
    cases1.put(Lazy.class, Tuple.of("Lazy.of(ImplementedClass::new)", "get()"));
    cases1.put(Tuple1.class, Tuple.of("new Tuple1<>(new ImplementedClass())", "_1"));
    java.util.Map<Class<?>, Tuple2<String, String>> cases2 = new java.util.HashMap<>();
    cases2.put(Either.class, Tuple.of("Either.right(new ImplementedClass())", "get()"));
    cases2.put(HashMap.class, Tuple.of("HashMap.of(42, new ImplementedClass())", "head()._2"));
    cases2.put(HashMultimap.class, Tuple.of("HashMultimap.withSeq().of(42, new ImplementedClass())", "head()._2"));
    cases2.put(Tuple2.class, Tuple.of("new Tuple2<>(42, new ImplementedClass())", "_2"));
    generate(cases1, cases2);
}
 
Example #22
Source File: MultimapTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void test1() throws IOException {
    Multimap<Object, Object> vavrObject = emptyMap().put("1", 2).put("2", 3).put("2", 4);
    java.util.Map<Object, List<Object>> javaObject = new java.util.HashMap<>();
    javaObject.put("1", Collections.singletonList(2));
    List<Object> list = new ArrayList<>();
    Collections.addAll(list, 3, 4);
    javaObject.put("2", list);

    String json = mapper().writer().writeValueAsString(vavrObject);
    Assertions.assertEquals(genJsonMap(javaObject), json);

    Multimap<?, ?> restored = (Multimap<?, ?>) mapper().readValue(json, clz());
    Assertions.assertEquals(restored, vavrObject);
}
 
Example #23
Source File: SimplePojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testHashMapOfTuple() throws Exception {
    Integer src00 = 1;
    String src010 = "A";
    String src011 = "B";
    Tuple2<String, String> src01 = Tuple.of(src010, src011);
    Tuple2<Integer, Tuple2<String, String>> src0 = Tuple.of(src00, src01);
    HashMap<Integer, Tuple2<String, String>> src = HashMap.ofEntries(src0);
    String json = MAPPER.writeValueAsString(new HashMapOfTuple().setValue(src));
    Assertions.assertEquals(json, "{\"value\":{\"1\":[\"A\",\"B\"]}}");
    HashMapOfTuple restored = MAPPER.readValue(json, HashMapOfTuple.class);
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #24
Source File: ParameterizedPojoTest.java    From vavr-jackson with Apache License 2.0 5 votes vote down vote up
@Test
void testHashMapOfTuple() throws Exception {
    Integer src00 = 1;
    String src010 = "A";
    String src011 = "B";
    Tuple2<String, String> src01 = Tuple.of(src010, src011);
    Tuple2<Integer, Tuple2<String, String>> src0 = Tuple.of(src00, src01);
    HashMap<Integer, Tuple2<String, String>> src = HashMap.ofEntries(src0);
    String json = MAPPER.writeValueAsString(new ParameterizedHashMapPojo<>(src));
    Assertions.assertEquals(json, "{\"value\":{\"1\":[\"A\",\"B\"]}}");
    ParameterizedHashMapPojo<java.lang.Integer, io.vavr.Tuple2<java.lang.String, java.lang.String>> restored =
            MAPPER.readValue(json, new TypeReference<ParameterizedHashMapPojo<java.lang.Integer, io.vavr.Tuple2<java.lang.String, java.lang.String>>>(){});
    Assertions.assertEquals(src, restored.getValue());
}
 
Example #25
Source File: XMLToJSON.java    From ts-reaktive with MIT License 5 votes vote down vote up
private Map<QName,XSParticle> getValidSubTags(XSElementDeclaration elmt) {
    if (!(elmt.getTypeDefinition() instanceof XSComplexTypeDefinition)) {
        return HashMap.empty();
    }
    
    XSComplexTypeDefinition type = (XSComplexTypeDefinition) elmt.getTypeDefinition();
    if (type.getParticle() == null || !(type.getParticle().getTerm() instanceof XSModelGroup)) {
        return HashMap.empty();
    }
    
    XSModelGroup group = (XSModelGroup) type.getParticle().getTerm();
    if (group.getCompositor() != XSModelGroup.COMPOSITOR_SEQUENCE && group.getCompositor() != XSModelGroup.COMPOSITOR_CHOICE) {
        return HashMap.empty();
    }
    
    // We don't care whether it's SEQUENCE or CHOICE, we only want to know what are the valid sub-elements at this level.
    XSObjectList particles = group.getParticles();
    Map<QName,XSParticle> content = HashMap.empty();
    for (int j = 0; j < particles.getLength(); j++) {
        XSParticle sub = (XSParticle) particles.get(j);
        if (sub.getTerm() instanceof XSElementDeclaration) {
            XSElementDeclaration term = (XSElementDeclaration) sub.getTerm();
            content = content.put(new QName(term.getNamespace(), term.getName()), sub);
        }
    }
    return content;
}
 
Example #26
Source File: InMemoryRetryRegistry.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
public InMemoryRetryRegistry(Map<String, RetryConfig> configs,
    RegistryEventConsumer<Retry> registryEventConsumer) {
    this(configs, registryEventConsumer, HashMap.empty());
}
 
Example #27
Source File: InMemoryTimeLimiterRegistry.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public TimeLimiter timeLimiter(final String name, final TimeLimiterConfig config) {
    return timeLimiter(name, config, HashMap.empty());
}
 
Example #28
Source File: InMemoryBulkheadRegistry.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Bulkhead bulkhead(String name, String configName) {
    return bulkhead(name, configName, HashMap.empty());
}
 
Example #29
Source File: InMemoryBulkheadRegistry.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public Bulkhead bulkhead(String name, BulkheadConfig config) {
    return bulkhead(name, config, HashMap.empty());
}
 
Example #30
Source File: InMemoryTimeLimiterRegistry.java    From resilience4j with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public TimeLimiter timeLimiter(final String name) {
    return timeLimiter(name, getDefaultConfig(), HashMap.empty());
}