Skip to content

Commit

Permalink
Amend
Browse files Browse the repository at this point in the history
  • Loading branch information
cbdyzj committed Aug 10, 2020
1 parent 6d8455c commit deb8b68
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
19 changes: 15 additions & 4 deletions src/main/java/org/jianzhao/sugar/Sugar.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,21 @@ public static <T> void forEach(List<T> list, Consumer<? super T> action) {
list.forEach(action);
}

public static <T> T findFirst(List<T> list, Predicate<? super T> predicate) {
List<T> filtered = filter(list, predicate);
if (isEmpty(filtered)) {
return null;
}
return filtered.get(0);
}

public static <T> boolean every(List<T> list, Predicate<? super T> predicate) {
if (isEmpty(list)) {
return false;
}
return list.stream().allMatch(predicate);
}

public static <T> List<T> distinct(List<T> list, Function<? super T, ?> keyExtractor) {
Objects.requireNonNull(keyExtractor);
Set<Object> seen = new HashSet<>();
Expand Down Expand Up @@ -174,10 +189,6 @@ public static <T, K, V> Map<K, List<V>> groupToMap(List<T> list,
Collectors.groupingBy(keyExtractor, Collectors.mapping(valueExtractor, Collectors.toList())));
}

public static <T> boolean includes(List<T> list, T item) {
return includes(list, Predicate.isEqual(item));
}

public static <T> boolean includes(List<T> list, Predicate<? super T> predicate) {
if (isEmpty(list)) {
return false;
Expand Down
18 changes: 15 additions & 3 deletions src/test/java/org/jianzhao/sugar/SugarTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -137,9 +137,8 @@ public void testGroupToMap() {
@Test
public void testIncludes() {
val list = listOf(3, 1, 4, 1, 5, 9, 2, 6);
assertTrue(includes(list, 3));
assertFalse(includes(list, 7));
assertFalse(includes(list, (Predicate<Integer>) it -> it < 0));
assertTrue(includes(list, Predicate.isEqual(5)));
assertFalse(includes(list, it -> it < 0));
}

@Test
Expand All @@ -152,4 +151,17 @@ public void testCollectionShortcut() {
);
assertTrue(c.get(1).get("2").contains(Pair.of("c", "C")));
}

@Test
public void testEvery() {
val list = listOf(3, 1, 4, 1, 5, 9);
assertTrue(every(list, it -> it > 0));
}

@Test
public void testFindFirst() {
val list = listOf(3, 1, 4, 1, 5, 9);
val first = findFirst(list, it -> it > 3);
assertEquals(4, first);
}
}

0 comments on commit deb8b68

Please sign in to comment.