From 7c19be7f34b932d696d839a092f05617400589f6 Mon Sep 17 00:00:00 2001 From: Pacien TRAN-GIRARD Date: Mon, 29 Feb 2016 17:25:37 +0100 Subject: Rewrite list mirroring function and add test --- src/ch/epfl/xblast/Lists.java | 43 ++++++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/ch/epfl/xblast/Lists.java b/src/ch/epfl/xblast/Lists.java index f468788..51e76b0 100644 --- a/src/ch/epfl/xblast/Lists.java +++ b/src/ch/epfl/xblast/Lists.java @@ -3,6 +3,8 @@ package ch.epfl.xblast; import java.util.ArrayList; import java.util.Collections; import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; /** * Lists utility class providing common operations on lists. @@ -13,30 +15,33 @@ import java.util.List; public final class Lists { /** - * Return a symmetric version of the list. + * Returns a reversed copy of the given list, leaving the original one unmodified. * - * @param l the input list - * @return mirroredList the mirrored list + * @param l the list to reverse + * @param the type of the list's elements + * @return a reversed copy of the list. + */ + public static List reversed(List l) { + List r = new ArrayList<>(l); + Collections.reverse(r); + return r; + } + + /** + * Returns a symmetric version of the list, without repeating the last element of the input list. + * For instance, mirrored([kay]) will return [kayak]. + * + * @param l the input list + * @param the type of the list's elements + * @return the mirrored list * @throws IllegalArgumentException if the given list is empty */ public static List mirrored(List l) { - if (l.size() == 0) { - throw new IllegalArgumentException(); - } - - List mirroredList = new ArrayList(); - List rightSide = new ArrayList(); - - for (int i = 0; i < l.size() - 1; i++) { - rightSide.add(l.get(i)); - } - - Collections.reverse(rightSide); - - mirroredList.addAll(l); - mirroredList.addAll(rightSide); + if (l == null || l.size() == 0) throw new IllegalArgumentException(); - return mirroredList; + return Stream + .concat(l.stream(), Lists.reversed(l).stream().skip(1)) + .collect(Collectors.toList()); } } -- cgit v1.2.3