skip to Main Content

I am using io.quarkus.redis.client.RedisClient which inside use Vert.x for a Redis Client in Java. When I use HSCAN method it return a list of key and values in differents rows like this:

enter image description here

The keys are 0,2,4… and the values are the JSONs. Is there a way to obtain a Map<key,value> instead of a list with a key and values mix in a elegant/clean way?

2

Answers


  1. You will need to iterate over the Response in order to get the map.

    Here is an example for Map<String, String> with for loop:

    Map<String, String> map = new HashMap<>();
    for (String key : results.getKeys()) {
        map.put(key, results.get(key).toString());
    }
    

    Here is the same example but using java lambdas:

    Map<String, String> map = result.getKeys().stream()
        .collect(Collectors.toMap(key -> key, key -> result.get(key).toString()));
    

    For your case with json you can just change the transformation function from .toString() to something that suits your need.

    Edit 1:

    As HSCAN returns array as defined:

    return a two elements multi-bulk reply, where the first element is a
    string representing an unsigned 64 bit number (the cursor), and the
    second element is a multi-bulk with an array of elements.

    There is not a simple solution to create a map but this is what I recommend:

    Iterator<Response> iterator = response.get(1).stream().iterator();
    Map<String, String> map = new HashMap<>();
        while (iterator.hasNext()) {
            map.put(iterator.next().toString(), iterator.next().toString());
        }
    
    Login or Signup to reply.
  2. You can do it with a simple for

            Map<String, String> result = new HashMap<>();
    
            for (int i = 0; i < source.length; i+=2) {
                result.put(source[i], source[i + 1]);
            }
    

    In Kotlin you can use a more elegant solution but I think this one works

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search