From f213ff8993588a9a0d63946e8a4f9b6975de3c95 Mon Sep 17 00:00:00 2001 From: Pacien TRAN-GIRARD Date: Wed, 11 May 2016 13:41:07 +0200 Subject: Add lists utils --- src/ch/epfl/xblast/Lists.java | 35 ++++++++++++++++++++++++++++++----- 1 file changed, 30 insertions(+), 5 deletions(-) (limited to 'src/ch/epfl') diff --git a/src/ch/epfl/xblast/Lists.java b/src/ch/epfl/xblast/Lists.java index 777fab2..7e3ba5e 100644 --- a/src/ch/epfl/xblast/Lists.java +++ b/src/ch/epfl/xblast/Lists.java @@ -2,7 +2,6 @@ package ch.epfl.xblast; import java.util.*; import java.util.stream.Collectors; -import java.util.stream.IntStream; import java.util.stream.Stream; /** @@ -207,10 +206,36 @@ public final class Lists { 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))); + Map m = new HashMap<>(); + Iterator ki = kl.iterator(); + Iterator vi = vl.iterator(); + + while (ki.hasNext() && vi.hasNext()) + m.put(ki.next(), vi.next()); + + return Collections.unmodifiableMap(m); + } + + /** + * Maps linearly two lists, adjusting their respective size by truncating the key list or completing the value list + * with null values. + * + * @param kl the keys list + * @param vl the values list + * @param the key type + * @param the value type + * @return the map + */ + public static Map linearAdjustedMap(List kl, List vl) { + if (Objects.isNull(kl) || Objects.isNull(vl)) + throw new IllegalArgumentException(); + + if (kl.size() <= vl.size()) + return Lists.linearMap(kl, vl.subList(0, kl.size())); + else + return Lists.linearMap( + kl, + concatenated(Arrays.asList(vl, Collections.nCopies(kl.size() - vl.size(), null)))); } /** -- cgit v1.2.3