Skip to content

Instantly share code, notes, and snippets.

@davidallsopp
Created January 22, 2014 13:41
Show Gist options
  • Save davidallsopp/8558894 to your computer and use it in GitHub Desktop.
Save davidallsopp/8558894 to your computer and use it in GitHub Desktop.
A generic Java method for taking the tails (progressively shorter sublists) of a List. Does not include the empty list (unlike the Haskell tails function), though this is trivially changed.
import java.util.*;
public class Tails {
/** Not including the empty list */
public static <A> List<List<A>> tails(List<A> xs) {
ArrayList<List<A>> tails = new ArrayList<List<A>>(xs.size());
for (int i = 0; i < xs.size(); i++) {
ArrayList<A> tail = new ArrayList<A>(xs.size() - i);
tails.add(tail);
for (List<A> ys : tails) {
ys.add(xs.get(i));
}
}
return tails;
}
public static void main(String[] args) {
String[] words = { "the", "cat", "sat", "on", "the", "mat" };
List<String> xs = Arrays.asList(words);
System.out.println(tails(xs));
// [[the, cat, sat, on, the, mat], [cat, sat, on, the, mat], [sat, on, the, mat], [on, the, mat], [the, mat], [mat]]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment