Skip to content

Commit

Permalink
feat(base.collection): methods for inserting an element at specified …
Browse files Browse the repository at this point in the history
…position in list

[skip ci]
  • Loading branch information
WakelessSloth56 committed Oct 11, 2022
1 parent 4565a89 commit 377de77
Showing 1 changed file with 19 additions and 0 deletions.
Expand Up @@ -12,6 +12,7 @@ public static <T> T getLast(List<T> list) {
return list.get(list.size() - 1);
}


public static <T> int indexOf(List<T> list, Predicate<T> predicate, int ordinal) {
for (int i = 0, l = list.size(); i < l; ++i) {
if (predicate.test(list.get(i))) {
Expand Down Expand Up @@ -47,4 +48,22 @@ public <T> int[] allIndexesOf(List<T> list, Predicate<T> predicate) {
.toArray();
}


public static <T> boolean add(List<T> list, int index, T element) {
try {
list.add(index, element);
return true;
} catch (IndexOutOfBoundsException e) {
return false;
}
}

public static <T> boolean addBefore(List<T> list, Predicate<T> refPredicate, T element) {
return add(list, indexOf(list, refPredicate), element);
}

public static <T> boolean addAfter(List<T> list, Predicate<T> refPredicate, T element) {
return add(list, indexOf(list, refPredicate) + 1, element);
}

}

0 comments on commit 377de77

Please sign in to comment.