英文:
How do I access an element in an Arraylist inside another Arraylist?
问题
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().equals(search)) {
containerHistoryList.add(j);
break; // No need to continue checking other containers in this journey
}
}
}
return containerHistoryList;
}
Here's a slightly improved version of your code with a minor optimization. Instead of continuing to iterate through the remaining containers in a journey after finding a match, the break
statement is used to exit the loop as soon as a match is found. This can improve efficiency since you don't need to keep checking other containers in the same journey once you've found the desired one.
英文:
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.
答案1
得分: 1
如果您熟悉使用Java 8的流操作,那么以下代码是可行的:
```java
List<Journey> containerhistorylist = history
.stream()
.filter(j -> j.getContainerList()
.stream()
.anyMatch(c -> c.getContainerId().contentEquals(search)))
.collect(Collectors.toList());
英文:
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());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论