Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't convert tuple list to hashmap java

I want to convert a javax.persistence.Tuple into a HashMap, but like this, it inserts the last element of the tuple and takes also the alias and data type. How can I improve this method so it takes values of the tuple?

public Map<String, Object> tuplesToMap(List<Tuple> data){
    Map<String, Object> values = new HashMap<>();
    data.forEach(tuple -> {
        tuple.getElements().forEach(
            element -> {
                values.put(element.getAlias(), tuple.get(element));
            }
        );
    });
    return values;
}
like image 567
rzz24118 Avatar asked Dec 09 '25 09:12

rzz24118


2 Answers

with java 8 is simply :

return data.stream()
    .collect(Collectors.toMap(
        t -> t.get(0, String.class),
        t -> t.get(1, Object.class)));
like image 94
Michael Cauduro Avatar answered Dec 11 '25 00:12

Michael Cauduro


Seems to be working :

public static List<Map<String/*UPPERCASE*/, Object>> jpaTuplesToMaps(
  List<javax.persistence.Tuple> data
){
    return data.stream()
        .map(tuple -> { // per each tuple of the input List
            // creating a new HashMap
            Map<String, Object> resultItem =  new HashMap<>();
            // filling the created HashMap with values of
            tuple.getElements().forEach( // each column of the tuple
                col -> { resultItem.put(col.getAlias(), tuple.get(col)); } 
            );
            // returning the created HashMap instead of  the current Tuple
            return resultItem;
        })
         // collecting & returning all the created HashMap-s as a List
        .collect(Collectors.toList());
}

But usualy both single & list conversions are required, so let's combine them :

public static Map<String/*UPPERCASE*/, Object> jpaTupleToMap(
    javax.persistence.Tuple data /*CASE INSENSITIVE*/
){
    Map<String, Object> result = 
        new HashMap<>(); // exactly HashMap since it can handle NULL keys & values
    data.getElements().forEach(
        col -> { result.put(col.getAlias(), data.get(col)); } 
    );
    return result;
}

//-------------------------
    
public static List<Map<String/*UPPERCASE*/, Object>> jpaTuplesToMaps(
    List<javax.persistence.Tuple> data /*CASE INSENSITIVE*/
){
    return data.stream() // List<Tuple> -> Tuple1,..TupleN
        .map(tuple -> jpaTupleToMap(tuple)) // Tuple1 -> HashMap1,..TupleN -> HashMapN
        .collect(Collectors.toList()); // HashMap1,..HashMapN -> List
}

like image 33
user16547619 Avatar answered Dec 10 '25 22:12

user16547619