Java collection filtering

I have something like this:

public class Foo {
  public String id;
}

and

Vector<Foo> foos;

I need to get an object from a collection by id.

In C #, I would do the following: foos.Where(o => o.id = 7)

What is the best way to do this in Java?

+3
source share
11 answers

You probably want to save your data in Map <Integer, Foo> instead of List <Foo>. For example, TreeMap will store everything in sorted order.

+5
source

For starters, I would suggest using ArrayList<Foo>, rather than Vector<Foo>- ArrayListalmost always preferable Vector.

API Google Collections, Iterables.filter. - , - -. , Java , Iterables.filter(collection, predicate), collection.filter(predicate). Java 7.

, filter Iterable<Foo> - , Iterables.find, Enumerable.First<T>(Func<T, bool>) LINQ.

+11

Google, :

Lists.newArrayList(Iterables.filter(foos, new Predicate<Foo>() {
  public boolean apply(Foo input) {
    return input != null && "7".equals(input.id);
  }
}));

Iterables.filter( Collections2.filter, ) , seh, . , newArrayList Google.

, Vector . , , List <Foo> Collection <Foo> . , Vector, ArrayList ( - , ).

+6

, Vector, ArrayList

ArrayList< Widget > widgets = ...

Widget found = null;

for ( Widget o : widgets )
{
  if ( o.id == 7 )
  {
    found = o;
    break;
  }

}
+3
Collection.binarySearch(List<T extends Comparable>, T key);

( - ), . Comparable.

: binarySearch (Collections.sort(..))

+1

ArrayList ( - - Collection ), Apache Commons Collections / ..

, Google Collections, Jon, .

+1

, Java - Foo , ( O (n)). , HashMap, foo .

"" :

public class ListOfFoos extends ArrayList<Foo> {

  public Foo getFooByIndex(String index) {
    // do your lookup here
  }

}

ListOfFoos ArrayList Collection, Foo .

+1

lambdaj. , , , - .

+1

. , , , .

Iterator, :

abstract class IteratorHusk<T> implements Iterator<T>
{
  @SuppressWarnings("unchecked")
  protected IteratorHusk()
  {
    value_ = nil();
  }


  @SuppressWarnings("unchecked")
  protected T nil()
  {
    return (T) NIL;
  }


  protected abstract T yield();


  private boolean tryPop()
  {
    value_ = yield();
    return NIL != value_;
  }


  @SuppressWarnings("unchecked")
  private T take()
  {
    final T current = value_;
    value_ = (T) NIL;
    return current;
  }


  public final boolean hasNext()
  {
    return NIL != value_ || tryPop();
  }


  public final T next()
  {
    if (NIL == value_ && !tryPop())
    {
      throw new NoSuchElementException();
    }
    return take();
  }


  public void remove()
  {
    throw new UnsupportedOperationException();
  }


  // We want to tolerate null as a possibly valid value.
  private static final Object NIL = new Object();
  private T value_;
}

2009 Java - , :

interface UnaryFunction<T, U>
{
  T eval(U argument);
}

:

class FilteringIterator<T> extends IteratorHusk<T>
{
  public FilteringIterator(Iterator<? extends T> iter,
                           UnaryFunction<Boolean, ? super T> pred)
  {
    iter_ = iter;
    pred_ = pred;
  }


  @Override
  protected T yield()
  {
    while (iter_.hasNext())
    {
      final T val = iter_.next();
      if (!pred_.eval(val))
      {
        return val;
      }
    }
    return nil();
  }


  private final Iterator<? extends T> iter_;
  private final UnaryFunction<Boolean, ? super T> pred_;
}

:

public static <T>
Iterator<T> lazyFilter(UnaryFunction<Boolean, ? super T> pred,
                       Iterator<? extends T> source)
{
  return new FilteringIterator<T>(source, pred);
}
0

sweetener .

:

Collection<Foo> filteredList = Collections.filter(foos, Criteria.newCriteria().add(Restrictions.equals("id", 7)));

0

, , O (log n):

Collection.binarySearch(List<T extends Comparable>, T key);

, HashMap<String, Object>, O (1).

ps: ArrayList Vector.

0

Source: https://habr.com/ru/post/1723769/


All Articles