如何计算ArrayList中的重复元素? [英] How to count duplicate elements in ArrayList?
问题描述
我需要分开并计算arraylist中有多少个值是相同的,并根据出现次数打印出来。
I need to separate and count how many values in arraylist are the same and print them according to the number of occurrences.
我有一个名为digits的arraylist :
I've got an arraylist called digits :
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765]
我创建了一个方法分隔每个值并将其保存到新数组。
I created a method which separates each value and saves it to a new array.
public static ArrayList<Integer> myNumbers(int z) {
ArrayList<Integer> digits = new ArrayList<Integer>();
String number = String.valueOf(z);
for (int a = 0; a < number.length(); a++) {
int j = Character.digit(number.charAt(a), 10);
digits.add(j);
}
return digits;
}
在此之后,我有了一个名为numbers的新数组。我在这个数组上使用sort
After this I've got a new array called numbers. I'm using sort on this array
Collections.sort(numbers);
我的ArrayList如下所示:
and my ArrayList looks like this:
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9]
它有:
2 times 0;
9 times 1;
4 times 2;
6 times 3;
5 times 4;
6 times 5;
5 times 6;
5 times 7;
5 times 8;
3 times 9;
我需要打印出数字字符串取决于它们的数量是多少
所以它假设看起来像这样:
1354678290
I need to print out the string of numbers depend on how many are they So it suppose to look like this : 1354678290
推荐答案
例如,使用Stream API。
By using the Stream API for example.
package tests;
import org.junit.Assert;
import org.junit.Test;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Duplicates {
@Test
public void duplicates() throws Exception {
List<Integer> items = Arrays.asList(1, 1, 2, 2, 2, 2);
Map<Integer, Long> result = items.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Assert.assertEquals(Long.valueOf(2), result.get(1));
Assert.assertEquals(Long.valueOf(4), result.get(2));
}
}
这篇关于如何计算ArrayList中的重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!