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
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;
}
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);
}
Array lists have a .contains(O Object)
function. Therefore, newList.contains(object)
will return true if found.
You can check out this resource for more details https://www.geeksforgeeks.org/arraylist-in-java/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.