There are multiple ways to find a element in a list. For example I have a list with some elements that have a unique ID. For a given ID I want to return the specific element from the list.
List example (just schema, not correct syntax):
//Element(String id, int value)
List<Element> list = new ArrayList();
int elemCount = 1000000;
for(int i = 0; i<elemCount; i++)
    list.add(new Element("id"+i, i));
Collections.shuffle(list);
Element e = getElement("id" + ThreadLocalRandom.current().nextInt(0, elemCount));
Given the following two methods, which does perform generally better based on the java internal implementation and why?
First method:
public Element getElement(String id) {
   return list.stream()
      .filter(e -> e.getId().equals(id))
      .findAny()
      .orElse(null);
}
Second method:
public Element getElement(String id) {
   for(Element e : list)
      if(e.getId().equals(id))
         return e;
   return null;
}
- "Element" as object is chosen just for example.
- Not relevant: Structure and size of the Element, PC performance etc.
- Java Version: 1.8.0_111
 
    

