Here you can find the source of getPrefixesAndSuffixes(List
Parameter | Description |
---|---|
T | The type of items contained in the list. |
items | The list of items. |
minSize | The minimum length of a prefix/suffix span (should be at least 1) |
maxSize | The maximum length of a prefix/suffix span |
paddingSymbol | Symbol to be included if we run out of bounds (e.g. if items has size 3 and we try to extract a span of length 4). |
includePrefixes | Whether to extract prefixes |
includeSuffixes | Whether to extract suffixes |
public static <T> List<List<T>> getPrefixesAndSuffixes(List<T> items, int minSize, int maxSize, T paddingSymbol, boolean includePrefixes, boolean includeSuffixes)
//package com.java2s; import java.util.*; public class Main { /**//from w w w . j a v a 2 s .c o m * Get all prefix/suffix combinations from a list. It can extract just * prefixes, just suffixes, or prefixes and suffixes of the same length. * * For example: * * <pre> * List<String> items = Arrays.asList("a", "b", "c", "d"); * System.out.println(CollectionUtils.getPrefixesAndSuffixes(items, 1, 2, null, true, true)); * </pre> * * would print out: * * <pre> * [[d], [a], [a, d], [d, c], [a, b], [a, b, c, d]] * </pre> * * and * * <pre> * List<String> items2 = Arrays.asList("a"); * System.out.println(CollectionUtils.getPrefixesAndSuffixes(items2, 1, 2, null, true, true)); * </pre> * * would print: * * <pre> * [[a], [a], [a, a], [a, null], [a, null], [a, null, a, null]] * </pre> * * @param <T> The type of items contained in the list. * @param items The list of items. * @param minSize The minimum length of a prefix/suffix span (should be at least 1) * @param maxSize The maximum length of a prefix/suffix span * @param paddingSymbol Symbol to be included if we run out of bounds (e.g. if items has * size 3 and we try to extract a span of length 4). * @param includePrefixes Whether to extract prefixes * @param includeSuffixes Whether to extract suffixes * @return All prefix/suffix combinations of the given sizes. */ public static <T> List<List<T>> getPrefixesAndSuffixes(List<T> items, int minSize, int maxSize, T paddingSymbol, boolean includePrefixes, boolean includeSuffixes) { assert minSize > 0; assert maxSize >= minSize; assert includePrefixes || includeSuffixes; List<List<T>> prefixesAndSuffixes = new ArrayList<>(); for (int span = minSize - 1; span < maxSize; span++) { List<Integer> indices = new ArrayList<>(); List<T> seq = new ArrayList<>(); if (includePrefixes) { for (int i = 0; i <= span; i++) { indices.add(i); } } if (includeSuffixes) { int maxIndex = items.size() - 1; for (int i = span; i >= 0; i--) { indices.add(maxIndex - i); } } for (int i : indices) { try { seq.add(items.get(i)); } catch (IndexOutOfBoundsException ioobe) { seq.add(paddingSymbol); } } prefixesAndSuffixes.add(seq); } return prefixesAndSuffixes; } }