Skip to content

Instantly share code, notes, and snippets.

@cfollet
Last active February 16, 2023 09:29
Show Gist options
  • Save cfollet/ea70c95736e66bae05a7c28105b8eb11 to your computer and use it in GitHub Desktop.
Save cfollet/ea70c95736e66bae05a7c28105b8eb11 to your computer and use it in GitHub Desktop.
Transform a Pair list to a Map grouping by key
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.commons.lang3.tuple.Pair;
public class Test
{
/**
* @param args
*/
public static void main(String[] args)
{
Set<Pair<Integer, String>> pairs = new HashSet<>(Arrays.asList(MutablePair.of(1, "A"), MutablePair.of(1, "B")));
Map<Integer, List<String>> map = pairs.stream()
.collect(Collectors.groupingBy(Pair::getKey, Collectors.mapping(Pair::getValue, Collectors.toList())));
map.forEach((k, v) -> System.out.println("key: " + k + " value:" + v));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment