How to filter an array in Java?

后端 未结 7 968
小蘑菇
小蘑菇 2020-12-10 02:01

How can I filter an array in Java?

I have an array of objects, for example cars:

Class:

public class Car{
    public int doors;
    public Ca         


        
相关标签:
7条回答
  • 2020-12-10 02:57

    The most efficient way to do this--if the predicate you're filtering on is inexpensive and you're accessing it with a single thread--is usually to traverse the list twice:

    public Car[] getFourDoors(Car[] all_cars) {
      int n = 0;
      for (Car c : all_cars) if (c.doorCount()==4) n++;
      Car[] cars_4d = new Car[n];
      n = 0;
      for (Car c : all_cars) if (c.doorCount()==4) cars_4d[n++] = c;
      return cars_4d;
    }
    

    This traverses the list twice and calls the test twice, but has no extra allocations or copying. The Vector-style methods traverse the list once, but allocates about twice the memory it needs (transiently) and copies every good element about twice. So if you are filtering a tiny fraction of the list (or performance isn't an issue, which very often it isn't), then the Vector method is good. Otherwise, the version above performs better.

    0 讨论(0)
提交回复
热议问题