Find if element exists in a List of objects Java

Hey I’m familiar with Java programming language and I got stuck with these problem.

I got a list of objects and the object class with 2 argument, a name and a version.

much appreciate for helpers!:-)

I want to check if the list contains the name in its list and and if so, take the higher version.

public MyObj(String name, int Ver){
      this.name = name;
      this.Ver = Ver;
  } 
List<MyObj> newList = new ArrayList<>(); <<< Trying to find here if a name already exists in these obj list

Answer

  1. Simple iteration and finding max by version:
public MyObj findMaxVersion(String name, List<MyObj> list) {
    MyObj res = null;
    for (MyObj m : list) {
        if (name.equals(m.getName()) && (null == res || res.getVer() < m.getVer())) {
            res = m;
        }
    }
    return res;
}
  1. Using Stream API: Stream::filter and Collectors.maxBy
public MyObj findMaxVersion(String name, List<MyObj> list) {
    return list.stream()
            .filter(m -> name.equals(m.getName()))
            .collect(Collectors.maxBy(Comparator.comparingInt(MyObj::getVer)))
            .orElse(null);
}

or even simpler using Stream::max:

public MyObj findMaxVersion(String name, List<MyObj> list) {
    return list.stream()
            .filter(m -> name.equals(m.getName()))
            .max(Comparator.comparingInt(MyObj::getVer))
            .orElse(null);
}