0

In my Spring Boot project I want to create a URL by concatenating several strings. The first strings I know how to get them, but to these I have to add some fields defined in a map.

How do I get from this map the list of its keys and for each key add the name of the key with its respective value?

This is the part of the code where I stopped:

@Value("${spring.route.source.protocol}")
private String protocol;

@Value("${spring.route.source.ip}")
private String ip;

@Value("${spring.route.source.root}")
private String root;

@Value("${spring.route.source.gets}")
private List<String> gets;

public void getWithRestTemplateGet1(Map<String, String> allGateAccessParams) {
        final String methodName = "getWithRestTemplateGet1()";
    try {
        startLog(methodName);

        List<String> keys = new ArrayList<String>();

        //HOW CAN I ADD KEY E VALUE FROM MAP TO URL?

        String url = protocol + ip + root + gets.get(0);
        HttpHeaders headers = new HttpHeaders();
        headers.setBasicAuth(username, password);
        HttpEntity request = new HttpEntity(headers);

        try {
            if (url.startsWith("https")) {
                restTemplate = getRestTemplateForSelfSsl();
            } else {
                restTemplate = new RestTemplate();
            }
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
            HttpStatus statusCode = response.getStatusCode();
            logger.info("STATUS GET1: " + statusCode);
            logger.info("URL GET1: " + url);
            logger.info("RESPONSE GET1: " + response);

            } catch (HttpStatusCodeException e) {
            logger.error(e.getMessage());
        }

        endLog(methodName);

    } catch (Exception e) {
        logger.error(e.getMessage());
    }
}

Can you help me?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
guidop21
  • 177
  • 3
  • 15
  • 1
    https://stackoverflow.com/questions/46898/how-do-i-efficiently-iterate-over-each-entry-in-a-java-map – Robert_Hall Jul 02 '21 at 10:36
  • There is no Map apparent in your code. I'm not sure what you are asking for. You extract values (V) from a Map using a key (K). You can invoke `keySet()` to get all of the keys in the Map. You can invoke `entrySet()` to get all of the key-value pairs. But most of the time you know the key and just invoke `containsKey(K)` or `get(K)` to check-for and retrieve the value. – vsfDawg Jul 02 '21 at 10:54
  • Does this answer your question? [How do I efficiently iterate over each entry in a Java Map?](https://stackoverflow.com/questions/46898/how-do-i-efficiently-iterate-over-each-entry-in-a-java-map) – jeanpic Jul 02 '21 at 10:58

2 Answers2

1

You can get entrySet() from map and iterate entrySet to getKey using getKey() and value using getValue() as below

for (Map.Entry<String, String> entry : allGateAccessParams.entrySet()) {
        System.out.println(entry.getKey() + ":" + entry.getValue());
    }
sanjeevRm
  • 1,541
  • 2
  • 13
  • 24
1

Here is a snippet using stream's reduce:

import java.text.MessageFormat;
import java.util.HashMap;

class Scratch {
    public static void main(String[] args) {
        HashMap<String, String> urlParamsMap = new HashMap<>();
        urlParamsMap.put("key1", "value1");
        urlParamsMap.put("key2", "value2");
        urlParamsMap.put("key3", "value3");

        String params = urlParamsMap.entrySet().stream()
                .map(entry -> MessageFormat.format("{0}={1}", entry.getKey(), entry.getValue()))
                .reduce((accumulator, next) -> MessageFormat.format("{0}{1}{2}",
                        accumulator,
                        accumulator.isEmpty() ? "" : "&",
                        next)
                ).orElse("");
        System.out.println("URL params: " + params);
    }
}

First we transform the stream of map entries to a stream of strings. Then we reduce the stream of strings to a single string containing the concatenation of all the strings. Finally it returns an empty string in case that the initial stream was empty. In this example, the result is:

URL params: key1=value1&key2=value2&key3=value3

For more info about how to use stream's reduce this post is very useful.

Fede Garcia
  • 677
  • 11
  • 18