From 766114c05bcd0b0388988aaf606e046857e6946a Mon Sep 17 00:00:00 2001 From: Pacien TRAN-GIRARD Date: Tue, 10 May 2016 17:10:31 +0200 Subject: Add lists and maps functions --- src/ch/epfl/xblast/Lists.java | 48 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) (limited to 'src/ch') diff --git a/src/ch/epfl/xblast/Lists.java b/src/ch/epfl/xblast/Lists.java index cc6a1c8..bf0cafa 100644 --- a/src/ch/epfl/xblast/Lists.java +++ b/src/ch/epfl/xblast/Lists.java @@ -2,6 +2,7 @@ package ch.epfl.xblast; import java.util.*; import java.util.stream.Collectors; +import java.util.stream.IntStream; import java.util.stream.Stream; /** @@ -181,4 +182,51 @@ public final class Lists { .collect(Collectors.toList())); } + /** + * Maps linearly two lists. + * + * @param kl the keys list + * @param vl the values list + * @param the key type + * @param the value type + * @return the map + */ + public static Map linearMap(List kl, List vl) { + if (Objects.isNull(kl) || Objects.isNull(vl) || kl.size() != vl.size()) + throw new IllegalArgumentException(); + + return Collections.unmodifiableMap(IntStream + .range(0, kl.size()).mapToObj(i -> i) + .filter(i -> Objects.nonNull(vl.get(i))) + .collect(Collectors.toMap(kl::get, vl::get))); + } + + /** + * Merges two maps Map and Map -> Map. + * + * @param m1 key maps + * @param m2 values maps + * @param the keys type + * @param the intermediate keys type + * @param the values type + * @return the traversing map + */ + public static Map traverseMaps(Map m1, Map m2) { + return Collections.unmodifiableMap(m1.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getKey, e -> m2.get(e.getValue())))); + } + + /** + * Returns an inverted copy of a bijective map. + * + * @param m the map to invert + * @param the keys type + * @param the values type + * @return the inverted map + */ + public static Map invertMap(Map m) { + return Collections.unmodifiableMap(m.entrySet().stream() + .collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey))); + } + } -- cgit v1.2.3