Reputation: 19
So I'm working on an object-oriented java project that deals with Load Management at a shipping company. A journey has an origin, location, content and destination. A journey has one or more containers where it is possible to monitor the temperature, humidity and pressure in the container. So I want to get all the journey's on which a given container has been on (the container's history). All containers used for any given journey are stored in that journey's "containerList" (arraylist).
So the idea is the method "containerHistory" should look through the arraylist "history"(which contains completed journeys) and for each journey in the "history" arraylist, should look through the array list "containerList" for each given journey and for each container in the array list "containerList" compare the given container's id to the one we are looking for( which in the below code will be represented by the string "search"
public ArrayList<Journey> containerHistory(String search, ArrayList<Journey> history){
ArrayList<Journey> containerhistorylist = new ArrayList<Journey>();
for(Journey j : history) {
for(Container c : j.getContainerList()) {
if (c.getContainerId().contentEquals(search)) {
containerhistorylist.add(j);
}
}
}
return containerhistorylist;
}
Any idea on how to improve this code or an alternative way of going about this will be greatly appreciated.
Upvotes: 0
Views: 50
Reputation: 467
If you are comfortable with using Java 8 streams then the following code is possible:
List<Journey> containerhistorylist = history
.stream()
.filter(j -> j.getContainerList()
.stream()
.anyMatch(c -> c.getContainerId().contentEquals(search)))
.collect(Collectors.toList());
Upvotes: 1