Java:在 ArrayList 中生成值的分布

标签 java arraylist

我有一个排序的 ArrayList 值。我想获得值的分布。例如:

  • 假设我有 500 个值,范围从 1 到 100。
  • 我想将它们分成几组,比如 10 组:值 1-10、11-20、21-30 等...
  • 我想要属于每个类别的 500 个值中每个值的计数。例如,500 人中有 5 人的值(value)在 1-10 之间,20 人在 11-20 之间,等等......
  • 但是,我不知道我的 ArrayList 中值的范围,它可能在 1-30 或 1-200 之间,但我想将它分成例如 10 个组。

有人知道怎么做吗?

最佳答案

使用 Guava让你在那个方向走得很远。下面是一些让您入门的代码:

// initialize the List with 500 random values between 1 and 200
// you'll probably supply your existing lists instead
final Random rand = new Random();
final List<Integer> list = new ArrayList<Integer>();
for(int i = 0; i < 500; i++){
    list.add(rand.nextInt(200)+1);
}

// create a multiset
final Multiset<Integer> multiset = TreeMultiset.create(list);

// create 10 partitions of entries
// (each element value may appear multiple times in the multiset
// but only once per partition)
final Iterable<List<Integer>> partitions =
    Iterables.partition(
        multiset.elementSet(),
        // other than aioobe, I create the partition size from
        // the number of unique entries, accounting for gaps in the list
        multiset.elementSet().size() / 9
    );

int partitionIndex = 0;
for(final List<Integer> partition : partitions){

    // count the items in this partition
    int count = 0;
    for(final Integer item : partition){
        count += multiset.count(item);
    }
    System.out.println("Partition " + ++partitionIndex + " contains "
            + count + " items (" + partition.size() + " unique) from "
            + partition.get(0) + " to "
            + partition.get(partition.size() - 1));
}

输出:

Partition 1 contains 53 items (20 unique) from 1 to 21
Partition 2 contains 49 items (20 unique) from 22 to 42
Partition 3 contains 58 items (20 unique) from 43 to 63
Partition 4 contains 60 items (20 unique) from 64 to 84
Partition 5 contains 58 items (20 unique) from 85 to 104
Partition 6 contains 44 items (20 unique) from 105 to 126
Partition 7 contains 46 items (20 unique) from 127 to 146
Partition 8 contains 54 items (20 unique) from 147 to 170
Partition 9 contains 50 items (20 unique) from 171 to 191
Partition 10 contains 28 items (8 unique) from 192 to 200

引用:

关于Java:在 ArrayList 中生成值的分布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5195457/

相关文章:

java - 多线程中线程不使用notify()退出等待状态

java - 如何在不循环的情况下顺序填充数组或数组列表?

java - 如何将空 arrayList 添加到从类创建的另一个 arrayList

java - 从数组列表中删除一个项目

Java 线程和关闭 Hook

java - Kotlin 是否支持 AIDL?

java - Volley 抽射。发送 JSONObject 作为参数

java - 继承,从子类调用方法

java - 使用分隔符对数组列表进行排序

python - 创建一个打印雪花的二维数组 PYTHON