Java中有find_if之类的东西吗?

发布于 2024-08-27 08:01:10 字数 116 浏览 4 评论 0原文

在 C++ 中,我可以使用 find_if 和谓词来查找容器中的元素。 Java中有类似的东西吗?集合上的 contains 方法使用 equals 并且不能参数化。

In C++, I can use find_if with a predicate to find an element in a container. Is there something like that in Java? The contains method on collections uses equals and can not be parameterized.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

千纸鹤 2024-09-03 08:01:10

您可以使用谓词来自 Google 收藏集。以下是教程和示例:

final Predicate<Car> expensiveCar = new Predicate<Car>() {
   public boolean apply(Car car) {
      return car.price > 50000;
   }
}

List<Car> cars = Lists.newArrayList();
cars.add(new Car("Ford Taurus", 20000));
cars.add(new Car("Tesla", 90000));
cars.add(new Car("Toyota Camry", 25000));
cars.add(new Car("McClaren F1", 600000));

final List<Car> premiumCars =
   Lists.immutableList(Iterables.filter(cars, expensiveCar));

您还可以查看此线程: 过滤集合的最佳方法是什么?

You can use Predicate from Google Collections. Here is the tutorial and an example from it:

final Predicate<Car> expensiveCar = new Predicate<Car>() {
   public boolean apply(Car car) {
      return car.price > 50000;
   }
}

List<Car> cars = Lists.newArrayList();
cars.add(new Car("Ford Taurus", 20000));
cars.add(new Car("Tesla", 90000));
cars.add(new Car("Toyota Camry", 25000));
cars.add(new Car("McClaren F1", 600000));

final List<Car> premiumCars =
   Lists.immutableList(Iterables.filter(cars, expensiveCar));

You can also look at this thread: What is the best way to filter a Collection?

苍白女子 2024-09-03 08:01:10

您可以使用 CollectionUtils.select 来自 Apache Commons。

例如,以下 C++ 代码

  bool isOdd (int i) {
    return i % 2 != 0;
  }
  ...
  vector<int> myvector;
  vector<int>::iterator it;

  myvector.push_back(10);
  myvector.push_back(25);
  myvector.push_back(40);
  myvector.push_back(55);

  it = find_if (myvector.begin(), myvector.end(), isOdd);
  cout << "The first odd value is " << *it << endl;

可以用 Java 编写为:

List<Integer> myList = Arrays.asList(10, 25, 40, 55);
List<Integer> oddNums = (List<Integer>) CollectionUtils.select(myList,
  new Predicate<Integer>() {
    public boolean apply(Integer i) {
      return i % 2 != 0;
    }
  }
);
System.out.println("The first odd value is "+oddNums.get(0));

请注意,与 C++ 示例不同,这将创建满足指定谓词的元素的新列表。

编辑:

正如 Matthew Flaschen 在下面的评论中所建议的,CollectionUtils.find 更接近您的需求。因此,使用find,上面的代码可以重写为:

List<Integer> myList = Arrays.asList(10, 25, 40, 55);
Integer firstOdd = (Integer) CollectionUtils.find(myList,
  new Predicate<Integer>() {
    public boolean apply(Integer i) {
      return i % 2 == 1;
    }
  }
);
System.out.println("The first odd value is "+firstOdd);

You can use CollectionUtils.select from Apache Commons.

For example, the following C++ code

  bool isOdd (int i) {
    return i % 2 != 0;
  }
  ...
  vector<int> myvector;
  vector<int>::iterator it;

  myvector.push_back(10);
  myvector.push_back(25);
  myvector.push_back(40);
  myvector.push_back(55);

  it = find_if (myvector.begin(), myvector.end(), isOdd);
  cout << "The first odd value is " << *it << endl;

can be written in Java as,

List<Integer> myList = Arrays.asList(10, 25, 40, 55);
List<Integer> oddNums = (List<Integer>) CollectionUtils.select(myList,
  new Predicate<Integer>() {
    public boolean apply(Integer i) {
      return i % 2 != 0;
    }
  }
);
System.out.println("The first odd value is "+oddNums.get(0));

Please note that, unlike in C++ example, this would create a new list of the elements satisfying the specified predicate.

EDIT :

As Matthew Flaschen has suggested in a comment below, CollectionUtils.find is even closer to what you need. So, with find, the above code can be rewritten as:

List<Integer> myList = Arrays.asList(10, 25, 40, 55);
Integer firstOdd = (Integer) CollectionUtils.find(myList,
  new Predicate<Integer>() {
    public boolean apply(Integer i) {
      return i % 2 == 1;
    }
  }
);
System.out.println("The first odd value is "+firstOdd);
も星光 2024-09-03 08:01:10

问题是使用像 find_if 这样的方法应该使代码更容易编写并且更容易阅读。然而,恕我直言,Java 不适合函数表示法,大多数时候,编写一个自然循环会更清晰、更简单。即代码更短,并且不需要大多数人不使用的库的知识。如果此功能是内置的并且 Java 支持闭包(如
看起来 Java 7 将会)那么使用谓词和函数方法会更有意义。

复杂性的一种衡量方法是计算符号的数量(将左括号/右括号算为一个)。使用这种复杂性衡量方法,大多数基于谓词的解决方案都具有更多符号,并且可能更复杂,并且开发人员难以阅读/维护。

在@Roman 给出的示例中,有 15 个符号。在循环示例中,有 10 个符号。

List<Car> premiumCars = new ArrayList();
for(Car car: cars)
   if(car.price > 50000)
      premiumCars.add(car);

在@Mario Fuscom 的示例中,有 9 个符号,在下面的示例中,有 9 个符号。但是,不需要非标准函数,任何了解 Java 的人都可以阅读/维护它。

List peopleOver30 = new ArrayList();
for(Person person: people)
   if(person.age > 30)
      peopleOver30.add(person);

以 @Rahul G 的最后一个例子 - 我讨厌独角兽,有 13 个符号。在循环示例中,有 8 个符号。

Integer firstOdd = null;
for(int i: myList) 
    if(i % 2 == 1) {
       firstOdd = i;
       break;
    } 

函数式编程可能对您更有意义,因为这是您的开发背景,但这并不意味着它是用 Java 表达这一点的自然或最简单的方法。 Java 7 可能会改变这一点......

The problem is that using a method like find_if should make the code simpler to write and easier to read. However, IMHO Java does not lend itself to functional notation and most of the time it is clearer and simpler to just write a natural loop. i.e. the code is shorter and doesn't require knowledge of libraries most people don't use. If this functionality was built in and Java supported Closures (as
it appears Java 7 will) then using predicates and functional methods would make more sense.

One measure of complexity is to count the number of symbols (counting open/close brackets as one) Using this measure of complexity, most predicate based solutions have more symbols and are possibly more complex and difficult for developers to read/maintain.

In the example given by @Roman, there are 15 symbols. In the loop example, there are 10 symbols.

List<Car> premiumCars = new ArrayList();
for(Car car: cars)
   if(car.price > 50000)
      premiumCars.add(car);

In the example by @Mario Fuscom, there is 9 symbols, in the following example there is 9 symbols. However, no non-standard functions are required and anyone who knows Java can read/maintain it.

List peopleOver30 = new ArrayList();
for(Person person: people)
   if(person.age > 30)
      peopleOver30.add(person);

Taking the last example from @Rahul G - I hate Unicorns, there are 13 symbols. In the loop example, there are 8 symbols.

Integer firstOdd = null;
for(int i: myList) 
    if(i % 2 == 1) {
       firstOdd = i;
       break;
    } 

Functional programming may make more sense to you because that is your development background, but this doesn't mean it is the natural or simplest way to express this in Java. Java 7 may change this....

阳光下的泡沫是彩色的 2024-09-03 08:01:10

在 Java 8 中,我们有 removeIf() ,它可以使用特定谓词从集合中删除元素。但我们没有像 find_if 这样的东西。但我们可以使用流 API 来实现这一点。

List<Integer> list = Arrays.asList(20,35,50,654);
int result = list.stream().filter(i-> i%2!=0).findFirst().orElse(0).intValue();
System.out.println(result);

In Java 8, we have removeIf() which removes elements from the collections with certain Predicate. But we do not have something like find_if. But we can use stream API to achieve this.

List<Integer> list = Arrays.asList(20,35,50,654);
int result = list.stream().filter(i-> i%2!=0).findFirst().orElse(0).intValue();
System.out.println(result);
娇女薄笑 2024-09-03 08:01:10

通过使用lambdaj,您可以以非常易读的方式轻松过滤java集合。例如以下语句:

select(persons, having(on(Person.class).getAge(), greaterThan(30)));

选择列表中年龄超过 30 岁的所有人员。

By using lambdaj you can easily filter a java collection in a very readable way. For example the following statement:

select(persons, having(on(Person.class).getAge(), greaterThan(30)));

selects all the persons in your list having more than 30 years.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文