TreeVisitor (@NotNull BlockTreeNode currentBlockNode) { Function<Object, BlockTreeNode> converter = el -> el instanceof DefaultMutableTreeNode ? (BlockTreeNode)((DefaultMutableTreeNode)el).getUserObject() : null; Set<SimpleNode> parents = new HashSet<>(); SimpleNode parent = currentBlockNode.getParent(); while (parent != null) { parents.add(parent); parent = parent.getParent(); } DefaultMutableTreeNode root = getRoot(); if (root != null) { parents.add((SimpleNode)root.getUserObject()); } return new TreeVisitor.ByComponent<>(currentBlockNode, converter) { @Override protected boolean contains(@NotNull BlockTreeNode pathComponent, @NotNull BlockTreeNode thisComponent) { return parents.contains(pathComponent); } }; }