Example usage for java.util.stream Collectors joining

List of usage examples for java.util.stream Collectors joining

Introduction

In this page you can find the example usage for java.util.stream Collectors joining.

Prototype

public static Collector<CharSequence, ?, String> joining(CharSequence delimiter, CharSequence prefix,
        CharSequence suffix) 

Source Link

Document

Returns a Collector that concatenates the input elements, separated by the specified delimiter, with the specified prefix and suffix, in encounter order.

Usage

From source file:Main.java

public static void main(String[] args) {
    Stream<String> s = Stream.of("a", "b", "c");

    String names = s.collect(Collectors.joining(", ", "Hello ", ". Goodbye."));

    System.out.println(names);/*  w  w  w .j  a  va 2 s. c  o m*/
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    List<Person> persons = Arrays.asList(new Person("Max", 18), new Person("Peter", 23),
            new Person("Pamela", 23), new Person("David", 12));

    String names = persons.stream().filter(p -> p.age >= 18).map(p -> p.name)
            .collect(Collectors.joining(" and ", "In Germany ", " are of legal age."));

    System.out.println(names);//from   w  w w.ja  v a2 s . c o  m
}

From source file:edu.mit.lib.mama.Mama.java

public static void main(String[] args) {

    Properties props = findConfig(args);
    DBI dbi = new DBI(props.getProperty("dburl"), props);
    // Advanced instrumentation/metrics if requested
    if (System.getenv("MAMA_DB_METRICS") != null) {
        dbi.setTimingCollector(new InstrumentedTimingCollector(metrics));
    }//from  ww  w .  j a  va 2s .c  om
    // reassign default port 4567
    if (System.getenv("MAMA_SVC_PORT") != null) {
        port(Integer.valueOf(System.getenv("MAMA_SVC_PORT")));
    }
    // if API key given, use exception monitoring service
    if (System.getenv("HONEYBADGER_API_KEY") != null) {
        reporter = new HoneybadgerReporter();
    }

    get("/ping", (req, res) -> {
        res.type("text/plain");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        return "pong";
    });

    get("/metrics", (req, res) -> {
        res.type("application/json");
        res.header("Cache-Control", "must-revalidate,no-cache,no-store");
        ObjectMapper objectMapper = new ObjectMapper()
                .registerModule(new MetricsModule(TimeUnit.SECONDS, TimeUnit.MILLISECONDS, true));
        try (ServletOutputStream outputStream = res.raw().getOutputStream()) {
            objectMapper.writer().withDefaultPrettyPrinter().writeValue(outputStream, metrics);
        }
        return "";
    });

    get("/shutdown", (req, res) -> {
        boolean auth = false;
        try {
            if (!isNullOrEmpty(System.getenv("MAMA_SHUTDOWN_KEY")) && !isNullOrEmpty(req.queryParams("key"))
                    && System.getenv("MAMA_SHUTDOWN_KEY").equals(req.queryParams("key"))) {
                auth = true;
                return "Shutting down";
            } else {
                res.status(401);
                return "Not authorized";
            }
        } finally {
            if (auth) {
                stop();
            }
        }
    });

    get("/item", (req, res) -> {
        if (isNullOrEmpty(req.queryParams("qf")) || isNullOrEmpty(req.queryParams("qv"))) {
            halt(400, "Must supply field and value query parameters 'qf' and 'qv'");
        }
        itemReqs.mark();
        Timer.Context context = respTime.time();
        try (Handle hdl = dbi.open()) {
            if (findFieldId(hdl, req.queryParams("qf")) != -1) {
                List<String> results = findItems(hdl, req.queryParams("qf"), req.queryParams("qv"),
                        req.queryParamsValues("rf"));
                if (results.size() > 0) {
                    res.type("application/json");
                    return "{ " + jsonValue("field", req.queryParams("qf"), true) + ",\n"
                            + jsonValue("value", req.queryParams("qv"), true) + ",\n" + jsonValue("items",
                                    results.stream().collect(Collectors.joining(",", "[", "]")), false)
                            + "\n" + " }";
                } else {
                    res.status(404);
                    return "No items found for: " + req.queryParams("qf") + "::" + req.queryParams("qv");
                }
            } else {
                res.status(404);
                return "No such field: " + req.queryParams("qf");
            }
        } catch (Exception e) {
            if (null != reporter)
                reporter.reportError(e);
            res.status(500);
            return "Internal system error: " + e.getMessage();
        } finally {
            context.stop();
        }
    });

    awaitInitialization();
}

From source file:Main.java

public static String collectionToString(Collection<?> collection) {
    return collection.stream().map(String::valueOf).collect(Collectors.joining(",", "(", ")"));
}

From source file:devbury.dewey.plugins.help.Help.java

@Override
public void onEvent(MessageEvent event) {
    Message message = event.getMessage();
    if (message.isCommand()) {
        if ("help".equals(message.getCommand())) {
            String response = usages.stream().flatMap(hp -> hp.usageSummary().getCommands().stream()).distinct()
                    .collect(Collectors.joining(", ", "I know about these commands: ", ""));

            chatServer.respondToMessage(message, response);
        } else {//  w w w.ja  v  a2  s  .co  m
            Matcher matcher = pattern.matcher(message.getCommand());
            if (matcher.matches()) {
                String command = matcher.group(1);
                String args = matcher.group(2);
                usages.stream().filter(hp -> hp.usageSummary().getCommands().contains(command))
                        .forEach(hp -> chatServer.respondToMessage(message,
                                hp.usageSummary().getTitle() + "\n" + hp.usageDetails(command, args)));
            }
        }
    }
}

From source file:devbury.dewey.hipchat.HipChatSettings.java

@PostConstruct
public void checkProperties() {
    Assert.hasText(email, "hipchat.email is not set!");
    Assert.hasText(password, "hipchat.password is not set!");
    Assert.hasText(apiToken, "hipchat.apiToken is not set!");
    if (!groupsToJoin.isEmpty()) {
        logger.info("{}", groupsToJoin.stream().collect(Collectors.joining(", ", "Only joining groups: ", "")));
    }//from  w  w w.  java2 s  .co m
}

From source file:io.github.jeddict.jcode.util.PersistenceUtil.java

public static void addProperty(PersistenceUnit punit, String key, String value) {
    Properties properties = punit.getProperties();
    if (properties == null) {
        properties = punit.newProperties();
        punit.setProperties(properties);
    }// ww  w  . j av  a 2  s.  c  om
    Property property = properties.newProperty();
    property.setName(key);
    property.setValue(value);

    Property existing = getProperty(properties.getProperty2(), key);

    if (existing != null) {
        existing.setValue(property.getValue());
    } else {
        properties.addProperty2(property);
    }
    System.out.println(Arrays.stream(punit.getProperties().getProperty2())
            .map(p -> p.getName() + '.' + p.getValue()).collect(Collectors.joining("|", "<", ">")));
}

From source file:net.jodah.failsafe.internal.actions.DoThrowAction.java

@Override
public String currentToString() {
    synchronized (current) {
        return current.stream().map(Object::toString).collect(Collectors.joining(",", name + "(", ") at "))
                + getDefinitionInfo();/*from w  ww.ja  v  a 2 s .  co  m*/
    }
}

From source file:ru.xxlabaza.popa.template.TemplaterFacade.java

private String bindingsToString(Map<String, Object> map) {
    if (map == null || map.isEmpty()) {
        return "{}";
    }/*from ww w.  ja va 2  s .  co m*/

    return map.entrySet().stream().map(entry -> {
        StringBuilder sb = new StringBuilder();
        sb.append(entry.getKey()).append('=');

        Object value = entry.getValue();
        if (value == null) {
            sb.append("");
        } else {
            String valueString = value.toString().replaceAll("\\r\\n|\\r|\\n", " ");
            if (sb.length() + valueString.length() > 80) {
                sb.append(valueString.substring(0, 80 - (sb.length() + 5))).append("...");
            } else {
                sb.append(valueString);
            }
        }
        return sb.toString();
    }).collect(Collectors.joining(",\n  ", "\n{\n  ", "\n}"));
}

From source file:net.jodah.failsafe.internal.actions.DoThrowAction.java

@Override
public String toString() {
    return arguments.stream().map(Object::toString).collect(Collectors.joining(",", name + "(", ")"));
}