问题
Good time of the day! Please tell me how to implement the following search correctly.
There are collection of elments like:
class Item {
int itemId;
List<Item> items;
}
How to determine exists an element with the specified itemId
in one of the collections items
of such elements? I understand that the recursive search method can help here, but I don't know how to implement it correctly.
回答1:
This is a graph structure. To search such structures you should use some searching algorithms like BFS/DFS . Example using Deepth First Search .
class Item {
private String name;
private boolean visisted;
private List<Item> items;
public boolean isVisisted() {
return visisted;
}
public void setVisisted(boolean visisted) {
this.visisted = visisted;
}
public List<Item> getItems() {
return items;
}
public void setItems(List<Item> items) {
this.items = items;
}
}
class DFS {
private Stack<Item> stack;
public DFS(Stack<Item> stack) {
this.stack = stack;
}
public void dfs(List<Item> items) {
for (Item i : items) {
if (!i.isVisisted()) {
i.setVisisted(true);
dfsStack(i);
}
}
}
public void dfsStack(Item rootItem) {
this.stack.add(rootItem);
rootItem.setVisisted(true);
while (!stack.isEmpty()) {
Item actualItem = this.stack.pop();
for (Item i : actualItem.getItems()) {
if (!i.isVisisted()) {
i.setVisisted(true);
this.stack.push(i);
}
}
}
}
}
回答2:
You can try this
Item myItem = items.stream()
.filter(item -> searchedId == item.getItemId())
.findAny() // or findFirst, depending on your needs
.orElse(null);
And then, you can create a method returning a boolean stating if myItem is null or not.
This method should look like
public boolean existsItem(int searchedId) {
Item myItem = items.stream()
.filter(item -> searchedId == item.getItemId())
.findAny() // or findFirst, depending on your needs
.orElse(null);
return myItem != null;
}
This method must be in your class.
You should also create getters and setters for your attributes itemId and items (it's a good practice and every IDE has a way to generate them with a simple clic on a menu).
No need to be more recursive than using Item in items attribute.
来源:https://stackoverflow.com/questions/63415198/find-element-in-collection-of-collection-elements