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

时间:2015-07-14 07:10:17

标签: java list

我有以下元素列表(称之为lst),例如:

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

我需要创建List<Container>其中

public class Container{

   private int value;
   private List<Integer> children;

   public Container(int i){ //impl
   }

   //other staff
}

如下:

Container(1)没有孩子,因此其子女提交了null

两个Container(2)都相同,只有一个孩子Container(1)

Container(5)有两个孩子Container(2),还有一个Container(2)

Container(43)有一个孩子Container(5)

等等。

所以,我可以按如下方式编写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;

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

1 个答案:

答案 0 :(得分:1)

你可以这样做:

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;

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