提示信息

Predicate操作Collection集合

乌拉拉 已关注

在Java中,Predicate是一个函数式接口,它可以用来操作和过滤Collection集合中的元素。Predicate接口的定义如下:

  1. @FunctionalInterface
  2. public interface Predicate<T> {
  3. boolean test(T t);
  4. }

Predicate接口中只有一个抽象方法test(),它接受一个参数并返回一个boolean类型的值。可以使用Predicate接口来实现一些通用的操作,比如过滤某个条件下的元素或者判断集合中的元素是否满足某个条件。

下面是一些常见的Predicate操作示例:

  1. 过滤集合中大于10的元素:
  1. List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
  2. Predicate<Integer> predicate = n -> n > 10;
  3. List<Integer> filtered = numbers.stream()
  4. .filter(predicate)
  5. .collect(Collectors.toList());
  6. System.out.println(filtered); // [11, 12, 13, 14, 15]
  1. 判断集合中是否存在某个元素:
  1. List<String> words = Arrays.asList("apple", "banana", "orange", "pear", "kiwi");
  2. Predicate<String> predicate = word -> word.equals("orange");
  3. boolean exists = words.stream()
  4. .anyMatch(predicate);
  5. System.out.println(exists); // true
  1. 判断集合中的所有元素是否满足某个条件:
  1. List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
  2. Predicate<Integer> predicate = n -> n > 0;
  3. boolean allMatch = numbers.stream()
  4. .allMatch(predicate);
  5. System.out.println(allMatch); // true

这些示例展示了Predicate接口在操作Collection集合时的一些常见用法,可以根据具体的需求,结合Predicate接口的方法来实现更多的操作。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
乌拉拉 关注 已关注

最近一次登录:2023-10-09 13:07:16   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图