java - How to generate List in a clearer way? -
i have following list of elements (call lst
), instance:
[1, 2, 2, 5, 78, 768, 6823, 43, 234]
i need create list<container>
public class container{ private int value; private list<integer> children; public container(int i){ //impl } //other staff }
as follows:
container(1)
has no children, therefore children filed = null
.
both container(2)
same , has 1 child container(1)
.
container(5)
has 2 children container(2)
, 1 more container(2)
.
container(43)
has 1 child container(5)
.
and forth.
so, write if-else
condition follows:
list<integer> lst; //the list of integers list<integer> leastelems = new arraylist<integer>(); integer leastelem = collections.min(lst); for(integer e : lst){ if(e.equals(leastelem)) leastelems.add(e); } list<integer> withourleastelems = new arraylist<>(lst); withourleastelems.removeall(leastelems) ; collections.sort(withourleastelems); list<container> containers = new arraylist<>(); //filling containers according requirements;
the code looks extremely wierd. i'd ask advice of how better?
you way:
list<integer> lst; //the list of integers lst.removeall(collections.singleton(collections.min(lst))); collections.sort(lst); list<container> containers = new arraylist<>(); //filling containers according requirements;
since use leastelem-list remove elements, equal leastelem need remove leastelem list , result same.
Comments
Post a Comment