Example usage for java.util Map forEach

List of usage examples for java.util Map forEach

Introduction

In this page you can find the example usage for java.util Map forEach.

Prototype

default void forEach(BiConsumer<? super K, ? super V> action) 

Source Link

Document

Performs the given action for each entry in this map until all entries have been processed or the action throws an exception.

Usage

From source file:com.sample.ecommerce.config.SchemaConfiguration.java

@PostConstruct
private void setup() throws DataStoreException {
    ExistsResponse existsResponse = client.prepareExists().setIndices(indexName).setTypes("schema").execute()
            .actionGet();//  ww w . j  av a2  s.c o m

    if (!existsResponse.exists()) {
        InputStream inputStream = SchemaConfiguration.class.getResourceAsStream("/default_schema/schema.json");

        Map<String, Object> schemaMap = asMap(getContentFromStream(inputStream));
        schemaMap.forEach((schemaId, schemaAsMap) -> {
            try {
                ((Map) schemaAsMap).put("id", schemaId);
                dataStore.createSchema(asString(schemaAsMap));
            } catch (DataStoreException ex) {
                LOGGER.error("Error Creating Schma", ex);
            }
        });

        schemaMap.keySet().forEach((String schemaId) -> {
            InputStream dataInputStream = null;
            try {
                dataInputStream = SchemaConfiguration.class
                        .getResourceAsStream("/default_schema/data/" + schemaId + ".json");
                if (dataInputStream != null) {
                    dataStore.delete(schemaId);
                    List dataValues = asList(getContentFromStream(dataInputStream));
                    dataValues.forEach(data -> {
                        try {
                            dataStore.create(schemaId, (Map<String, Object>) data);
                        } catch (DataStoreException ex) {
                            LOGGER.error("Error Creating Schma", ex);
                        }
                    });
                }

            } catch (Exception e) {
                Logger.getLogger(SchemaConfiguration.class.getName()).log(Level.SEVERE, null, e);
            } finally {
                try {
                    if (dataInputStream != null) {
                        dataInputStream.close();
                    }

                } catch (IOException ex) {
                    LOGGER.error("Error Creating Schma", ex);
                }
            }

        });
    }

}

From source file:at.christophwurst.orm.consoleclient.StatisticsCommands.java

public void registerCommands(Client client) {
    client.registerCommand("statistics:project:employee", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("project id");
        statisticsService.getEmployeeTimeOnProjectPerEmployee(id).forEach((Employee e, Long time) -> {
            time = time / (1000 * 3600);
            System.out.println("  - " + e + ": " + time + "h");
        });/*  w  w w .java  2 s . c o  m*/
    });

    client.registerCommand("statistics:project:sprint", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("project id");
        statisticsService.getSprintTime(id).forEach((Sprint sprint, Long time) -> {
            time = time / (1000 * 3600);
            System.out.println("  - " + sprint + ": " + time + "h");
        });
    });

    client.registerCommand("statistics:project:requirements", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("project id");
        statisticsService.getRequirementTime(id).forEach((Requirement r, Long time) -> {
            time = time / (1000 * 3600);
            System.out.println("  - " + r + ": " + time + "h");
        });
    });

    client.registerCommand("statistics:employee:project", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("employee id");
        statisticsService.getEmployeeTimeOnProject(id).forEach((Project proj, Long time) -> {
            time = time / (1000 * 3600);
            System.out.println("  - " + proj + ": " + time + "h");
        });
    });

    client.registerCommand("statistics:employee:projectsprint", (consoleInterface) -> {
        Long id = consoleInterface.getLongValue("employee id");
        statisticsService.getEmployeeTimeOnSprint(id).forEach((Project proj, Map<Sprint, Long> projStat) -> {
            System.out.println("  - Project " + proj);
            projStat.forEach((Sprint sprint, Long time) -> {
                time = time / (1000 * 3600);
                System.out.println("    - Sprint " + sprint + ": " + time + "h");
            });
        });
    });

}

From source file:se.uu.it.cs.recsys.service.resource.FrequenPatternResource.java

private Map<Set<Course>, Integer> convertToCourse(Map<Set<Integer>, Integer> patterns) {

    Map<Set<Course>, Integer> output = new HashMap<>();

    patterns.forEach((k, v) -> {
        Set<se.uu.it.cs.recsys.persistence.entity.Course> courses = this.courseRepository.findByAutoGenIds(k);

        Set<Course> apiCourses = new HashSet<>();

        courses.forEach(entity -> apiCourses.add(CourseConverter.convert(entity)));

        output.put(apiCourses, v);//from w  ww.ja v a2 s  .  c  om

    });

    return output;
}

From source file:org.springframework.boot.devtools.settings.DevToolsSettings.java

private Map<String, Pattern> getPatterns(Map<?, ?> properties, String prefix) {
    Map<String, Pattern> patterns = new LinkedHashMap<>();
    properties.forEach((key, value) -> {
        String name = String.valueOf(key);
        if (name.startsWith(prefix)) {
            Pattern pattern = Pattern.compile((String) value);
            patterns.put(name, pattern);
        }//from  w  w  w .j a v  a  2s . c o m
    });
    return patterns;
}

From source file:org.apache.tomee.security.cdi.TomEESecurityServletAuthenticationMechanismMapper.java

public void init(@Observes @Initialized(ApplicationScoped.class) final ServletContext context) {
    final Map<String, ? extends ServletRegistration> servletRegistrations = context.getServletRegistrations();
    servletRegistrations.forEach((servletName, servletRegistration) -> {
        try {/*from   w ww .j  ava2  s  . co m*/
            final Class<?> servletClass = Thread.currentThread().getContextClassLoader().loadClass(servletName);
            if (servletClass.isAnnotationPresent(BasicAuthenticationMechanismDefinition.class)) {
                servletAuthenticationMapper.put(servletName,
                        CDI.current().select(BasicAuthenticationMechanism.class).get());
            }

            if (servletClass.isAnnotationPresent(FormAuthenticationMechanismDefinition.class)) {
                servletAuthenticationMapper.put(servletName,
                        CDI.current().select(FormAuthenticationMechanism.class).get());
            }

        } catch (final ClassNotFoundException e) {
            // Ignore
        }
    });

    final Set<HttpAuthenticationMechanism> availableBeans = authenticationMechanisms.stream()
            .collect(Collectors.toSet());
    availableBeans.removeAll(servletAuthenticationMapper.values());
    availableBeans.remove(defaultAuthenticationMechanism);

    if (availableBeans.size() == 1) {
        defaultAuthenticationMechanism.setDelegate(availableBeans.iterator().next());
    } else if (availableBeans.size() > 1) {
        throw new IllegalStateException("Multiple HttpAuthenticationMechanism found "
                + availableBeans.stream().map(b -> substringBefore(b.getClass().getSimpleName(), "$$"))
                        .collect(toList())
                + " " + "without a @WebServlet association. "
                + "Deploy a single one for the application, or associate it with a @WebServlet.");
    }
}

From source file:org.kie.workbench.common.forms.dynamic.backend.server.context.generation.dynamic.impl.fieldProcessors.NestedFormFieldValueProcessor.java

protected void writeValues(Map<String, Object> values, Object model) {
    if (model == null) {
        return;/*from   w  w  w.  ja  va  2  s. c om*/
    }
    values.forEach((property, value) -> {
        try {
            if (property.equals(MapModelRenderingContext.FORM_ENGINE_OBJECT_IDX)
                    || property.equals(MapModelRenderingContext.FORM_ENGINE_EDITED_OBJECT)) {
                return;
            }
            if (PropertyUtils.getPropertyDescriptor(model, property) != null) {
                BeanUtils.setProperty(model, property, value);
            }
        } catch (Exception e) {
            getLogger().warn("Error modifying object '{}': cannot set value '{}' to property '{}'", model,
                    value, property);
            getLogger().warn("Caused by:", e);
        }
    });
}

From source file:org.lecture.service.CompilerServiceImpl.java

public CompilationResult compileSources(Map<String, String> sources) {
    StringCompiler compiler = new StringCompiler();
    sources.forEach(compiler::addCompilationTask);
    return compiler.startCompilation();
}

From source file:com.mec.Services.SuperiorService.java

private List<EstablecimientoPost> buscate() throws IOException {
    Map<String, List<String>> s = superior.getAll();
    List<EstablecimientoPost> list = new ArrayList<>();
    s.forEach((carrera, cueAnexos) -> {
        if (carrera != null && cueAnexos != null) {
            cueAnexos.forEach(cueAnexo -> {
                Integer cue = 0, anexo = 0;
                EstablecimientoPost l = null;
                try {
                    cue = Integer.parseInt(cueAnexo.substring(0, 7));
                    anexo = Integer.parseInt(cueAnexo.substring(8));
                    l = posgreDAO.getByCueAnexo(cue, anexo);

                } catch (Exception e) {

                }//from   www.  j a  v  a2  s  .co m
                if (l != null) {
                    if (list.contains(l)) {
                        list.get(list.indexOf(l)).getLocalizacion().forEach(loc -> {
                            loc.getOrientacion().add(carrera);
                        });
                    } else {
                        l.getLocalizacion().forEach(loc -> {
                            loc.getOrientacion().add(carrera);
                        });
                        list.add(l);
                    }
                }
            });
        }

    });

    list.forEach(e -> {
        initGeo(e);
    });

    return list;
}

From source file:com.mec.Services.VoteroService.java

public Map<String, List<Establecimiento>> withFilter(float my_lat, float my_lon, double distanceKM)
        throws IOException {
    Map<String, List<Establecimiento>> todo = getAll();
    GeoDistance gd = new GeoDistance(my_lat, my_lon);
    todo.forEach((k, v) -> {
        v.stream().forEach(est -> {//from  w  w  w  .  j  av  a 2 s .c  om
            est.getEstablecimiento().getLocalizacion().forEach(l -> {
                l.getDomicilios().forEach(d -> {
                    if (d.getGeo() != null) {
                        double distancia = gd.getDistanceTo(((BigDecimal) d.getGeo().getLatitud()).floatValue(),
                                ((BigDecimal) d.getGeo().getLongitud()).floatValue());
                        est.setDistancia(distancia);
                    } else {
                        System.out.println("geo null: " + est.getEstablecimiento().getCue());
                    }
                });
            });
        });//establecimientos
    });
    return todo;
}

From source file:io.gravitee.repository.mongodb.management.internal.event.EventMongoRepositoryImpl.java

@Override
public Page<EventMongo> search(Map<String, Object> values, long from, long to, int page, int size) {
    Query query = new Query();

    // set criteria query
    values.forEach((k, v) -> {
        if (v instanceof Collection) {
            query.addCriteria(Criteria.where(k).in((Collection) v));
        } else {//from w ww  .  j a  va  2  s . c  o  m
            query.addCriteria(Criteria.where(k).is(v));
        }
    });

    // set range query
    query.addCriteria(Criteria.where("updatedAt").gte(new Date(from)).lt(new Date(to)));

    // set sort by updated at
    query.with(new Sort(Sort.Direction.DESC, "updatedAt"));

    // set pageable
    query.with(new PageRequest(page, size));

    List<EventMongo> events = mongoTemplate.find(query, EventMongo.class);
    long total = mongoTemplate.count(query, EventMongo.class);

    Page<EventMongo> eventsPage = new Page<>(events, page, size, total);

    return eventsPage;
}