java - Finding the same value in the list<Object>? -
here many customizablemenus objects in list, want find if 2 customizablemenus objects contains same cust.getcomponentstate(); want find getcomponentstate(); here posting code.how can value list.
for(customizablemenus cust : ra.getaction().getcustomizablemenu()){ cust.getcomponentid(); cust.getcomponentidentification(); cust.getcomponentname(); cust.getcomponentstate(); custlist.add(cust); system.out.println("cust menus in ctrl custid "+ cust.getcomponentid()+"component name "+cust.getcomponentname()+"identification "+cust.getcomponentidentification()); }
you have compare n
items n
items run loop complexity o(n^2)
plus complexity of if statements:
whatever using array
,list
,map
,.. logic same.
general code:
for(item item1:yourlist.getitems()){ for(item item2:yourlist.getitems()) if(item2!=item1) //not compare item it's self //if have same component state if(item2.getcomponentstate() == item1.getcomponentstate()){ //..do } }
about situation:
for(customizablemenus cust1 : ra.getaction().getcustomizablemenu()){ for(customizablemenus cust2 : ra.getaction().getcustomizablemenu()){ if(cust1 != cust2 ) //not compare item it's self //if have same component state if(cust1 .getcomponentstate() == cust2 .getcomponentstate()){ //..do } }
edit:
why need use
if(cust1 != cust2 )
you have loops here.let's see 2 examples:
entering loop first time getting first item of list,so cust1
(is first element of list).now entering second loop , getting first item of list again.so cust1
, cust2
same(the first item of list).we don't want compare them (cust1 .getcomponentstate() == cust2 .getcomponentstate())
cause same item.
the second loop continues comparing cust1
(which still first item of list) cust2
second item of list.and on...
when second loop exits,then cust1
becoming second item of list,after entering second loop.first compare cust1
(which second item of list) cust2
(which first item of list) . compare cust1
cust2
(which happens second item of list,but cust1
second item of list,so don't need compare them (cust1 .getcomponentstate() == cust2 .getcomponentstate())
cause same item.
i hope understand why using if(cust1 != cust2 )
finally:
this solution academic purposes. check link below better solutions in term of performance.
http://javarevisited.blogspot.gr/2015/06/3-ways-to-find-duplicate-elements-in-array-java.html
Comments
Post a Comment