创建n个数组列表

时间:2013-06-05 13:53:45

标签: java

现在我有一个名为" ID"它包含一个数字列表,如:

3  3  3  3  3  6  6  6  6  6  7  7  7  7  8  8  8  
每次程序运行时,

ID都会有所不同。

有没有办法可以创造一种情况,我可以分解我的" ID"数组列表到只包含相同数字的较小数组列表?我无法找到一种方法来创建可以根据有多少不同数字生成一定数量的新数组列表的代码" ID"。

ArrayList<Double> ID = new ArrayList<Double>();
//ID is filled by a text file that will vary but will look something like 
    // 2 2 2 2 2 2 4 4 4 4 4 4 4 6 6 6 6 6 6 6 7 7 7 7 8 8 (all whole numbers)

我想要什么

ArrayList<Double> newArray1 = new ArrayList<Double>();
//contains 2 2 2 2 2 2 
ArrayList<Double> newArray2 = new ArrayList<Double>();
//contains 4 4 4 4 4 4 4
ArrayList<Double> newArray3 = new ArrayList<Double>();
//contains 6 6 6 6 6 6 6

等等

4 个答案:

答案 0 :(得分:1)

要获得唯一值,请使用Set并让java完成工作。

要了解您拥有的每种价值的数量,您可以随时使用Map<Integer,Integer>

答案 1 :(得分:0)

  

只包含相同数字的较小数组列表?

所以你想要一个充满元素的arraylist都是平等的?你为什么要这样做?

您只需使用每个数字的计数器即可实现您想要的效果。然后,您可以将所有计数器保存在Map

Map<String, Integer> countMap = new HashMap<>();

为了计算ID,您可以使用如下方法:

public void incrementForID(String id, Map<String, Integer> countMap) {
    Integer c = countMap.get(id);
    if(c == null) {
         c = 0;
    }
    coutmap.put(id, c.intValue()+1);
}

答案 2 :(得分:0)

public class OhMyGod {

    public List<ArrayList<Object>> answerThisQuestion(List<File> files) {

        ArrayList<ArrayList<Object>> returnValue = new ArrayList<>();

        for (File f: files) {
            int numberOfLists = magicallyGuessHowMany(f);
            for (int i = numberOfLists -1; numberOfLists != 0; numberOfLists--) {
                returnValue.add(new ArrayList<>());
            }
        }
        return returnValue;
    }

    public int magicallyGuessHowMany(File f){
        // answer my question here
    }
}

我想这不会解决您的需求。但是,它会回答您的问题

答案 3 :(得分:-1)

您可以尝试使用List<ArrayList<MyObject>>

因此,您可以根据需要添加任意数量的ArrayList

相关问题