如何以更清晰的方式生成List?

时间:2021-03-11 14:58:27

I have the following list of elements (Call it lst), for instance:

我有以下元素列表(Call it lst),例如:

[1, 2, 2, 5, 78, 768, 6823, 43, 234]

I need to create the List<Container> where

我需要创建List

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 its children filed = null.

容器(1)没有子节点,因此其子节点= null。

Both Container(2) are the same and has one child Container(1).

Container(2)都是相同的,并且有一个子Container(1)。

Container(5) has two children Container(2) and One more Container(2).

容器(5)有两个子容器(2)和一个容器(2)。

Container(43) has one child Container(5).

容器(43)具有一个子容器(5)。

and so forth.

等等。

So, I could write if-else condition as follows:

所以,我可以写if-else条件如下:

List<Integer> lst; //the list of the 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 the containers according to the requirements;

The code looks extremely wierd. So I'd like to ask you advice of how to do it better?

代码看起来非常奇怪。所以我想问你如何做得更好的建议?

1 个解决方案

#1


1  

You could do it this way:

你可以这样做:

List<Integer> lst; //the list of the integers
lst.removeAll(Collections.singleton(Collections.min(lst)));

Collections.sort(lst);

List<Container> containers = new ArrayList<>();
//filling the containers according to the requirements;

Since you only use the leastElem-List to remove all elements, which are equal to leastElem you need only to remove all leastElem from the list and the result will be the same.

由于您只使用leastElem-List删除所有等于leastElem的元素,因此您只需要从列表中删除所有leastElem,结果将是相同的。

#1


1  

You could do it this way:

你可以这样做:

List<Integer> lst; //the list of the integers
lst.removeAll(Collections.singleton(Collections.min(lst)));

Collections.sort(lst);

List<Container> containers = new ArrayList<>();
//filling the containers according to the requirements;

Since you only use the leastElem-List to remove all elements, which are equal to leastElem you need only to remove all leastElem from the list and the result will be the same.

由于您只使用leastElem-List删除所有等于leastElem的元素,因此您只需要从列表中删除所有leastElem,结果将是相同的。