Skip to content

Instantly share code, notes, and snippets.

@thrakt
Last active August 25, 2017 15:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thrakt/31031f0f489d797a8e86e39d9e1841e2 to your computer and use it in GitHub Desktop.
Save thrakt/31031f0f489d797a8e86e39d9e1841e2 to your computer and use it in GitHub Desktop.
Prepare for instant codes
import java.util.stream.*;
import java.util.*;
public class Tool {
public static Map<Integer, List<Integer>> reverseArrayValue(int[] array) {
Map<Integer, List<Integer>> result = new HashMap<>();
for (int i = 0; i < array.length; i++) {
result.putIfAbsent(array[i], new ArrayList<Integer>());
result.get(array[i]).add(i);
}
return result;
}
public static <T> List<T> subtractListBfromA(List<T> a, List<T> b) {
List<T> bClone = new ArrayList<>(b);
return a.stream().flatMap(t -> {
if (bClone.contains(t)) {
bClone.remove(t);
return Stream.empty();
}
return Stream.of(t);
}).collect(Collectors.toList());
}
public static <T> List<List<T>> splitArray(T[] array, int n) {
List<List<T>> result = new ArrayList<>(array.length / n);
List<T> buf = new ArrayList<>(n);
for (int i = 0; i < array.length; i++) {
buf.add(array[i]);
if (i % n == n - 1) {
result.add(buf);
buf = new ArrayList<>(n);
}
}
if (buf.size() > 0) {
result.add(buf);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment