@@ -112,17 +112,24 @@ public Optional<SubMenuItem> getSubMenuById(int parentId) {
112112 * @param id the id of the object to find.
113113 * @return the menu at the given id
114114 */
115- public Optional <MenuItem > getMenuById (int id ) {
115+ @ SuppressWarnings ("unchecked" )
116+ public <T extends MenuItem > Optional <T > getMenuById (int id ) {
116117 var state = menuStates .get (id );
117118 if (state != null ) {
118- return Optional .of (state .getItem ());
119+ return Optional .of (( T ) state .getItem ());
119120 }
120121
121122 // shortcut to find the submenu by ID if possible before going through everything.
122- var maybeSubMenuId = getAllSubMenus ().stream ().filter (item -> item .getId () == id ).findFirst ();
123- if (maybeSubMenuId .isPresent ()) return maybeSubMenuId ;
123+ var maybeItem = getAllSubMenus ().stream ().filter (item -> item .getId () == id ).map (m -> (T )m ).findFirst ();
124+ if (maybeItem .isEmpty ()) {
125+ maybeItem = getAllMenuItems ().stream ().filter (item -> item .getId () == id ).map (m -> (T ) m ).findFirst ();
126+ }
127+
128+ // store a state object for the menu item, then we know for sure the next lookup is fast.
129+ maybeItem .ifPresent (t -> menuStates .put (id , stateForMenuItem (t , MenuItemHelper .getDefaultFor (t ),
130+ false , false )));
124131
125- return getAllMenuItems (). stream (). filter ( item -> item . getId () == id ). findFirst () ;
132+ return maybeItem ;
126133 }
127134
128135 /**
@@ -159,8 +166,10 @@ public void replaceMenuById(SubMenuItem subMenu, MenuItem toReplace) {
159166
160167 // Now we update the "state" which also acts like a cache of menu items for lookup
161168 if (menuStates .containsKey (toReplace .getId ())) {
162- var oldState = menuStates .get (toReplace .getId ());
163- menuStates .put (toReplace .getId (), stateForMenuItem (oldState , toReplace , oldState .getValue ()));
169+ menuStates .compute (toReplace .getId (), (k , oldState ) -> {
170+ var v = oldState != null ? oldState .getValue () : MenuItemHelper .getDefaultFor (toReplace );
171+ return stateForMenuItem (oldState , toReplace , v );
172+ });
164173 }
165174
166175 // lastly if the item was a submenu, we need change the top level submenu list as well.
0 commit comments