Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Map<A, B> to List< Pair<A,B> > - is this the most efficient where A, B are classes?

I have a Map pairs and want to turn this into an ArrayList with Pair objects.

I know i can do something like this

List<Pair<A,B>> nvpList = new ArrayList<Pair<A,B>>(2);
for(Map.Entry<String, String> entry : pairs.entrySet()){
  Pair n = new Pair(entry.getKey(), entry.getValue());
  nvpList.add(n);
}

How can we do this in java8 using streams?

like image 704
rishabhjainps Avatar asked Sep 02 '25 01:09

rishabhjainps


1 Answers

Considering generics, you can perform that as:

<A, B> List<Pair<A, B>> convertMapToListOfPairs(Map<A, B> pairs) {
    return pairs.entrySet().stream()
            .map(entry -> Pair.of(entry.getKey(), entry.getValue()))
            .collect(Collectors.toList());
}
like image 192
Naman Avatar answered Sep 08 '25 10:09

Naman