for(int i=0; i<arr.size(); ++i){
oc = Collections.frequency(arr, arr.get(i));
System.out.print(oc + " "+ arr.get(i) +" ");
arr.remove(i);
}
The main idea is to output how many times every element in sequence occurs. For example
1 1 2 3 3 3 10 10
here the output is
2 1 1 2 3 3 2 10
It is like two ones, one element of two, 3 elements of 3, and 2 elements of 10.
This is buggy, for example it is not working for this case
1 1 1 2 2 1 1 1
What is wrong? Any other algorithms?
The problem is that inside the for
loop you remove an element ( arr.remove(i)
) so the remaining elements get shifted and when i
gets incremented, you skip one element. Removing an element also changes its frequency, so don't do that.
Do something like this:
List<String> arr = Arrays.asList("a", "a", "b", "a", "a");
for (String s : arr)
System.out.println("element: " + s
+ ", count: " + Collections.frequency(arr, s));
If an element is in the list multiple times, this will print it multiple times. Use a HashSet
to remember if an element was already printed, and do not print it again:
List<String> arr = Arrays.asList("a", "a", "b", "a", "a");
Set<String> printed = new HashSet<>();
for (String s : arr) {
if (printed.add(s)) // Set.add() also tells if the element was in the Set!
System.out.println("element: " + s
+ ", count: " + Collections.frequency(arr, s));
}
Output:
element: a, count: 4
element: b, count: 1
Alternatively you can add all elements of the original list to a Set
(which will ensure every element is contained only once), and iterate over this set, but count in the original array:
List<String> arr = Arrays.asList("a", "a", "b", "a", "a");
for (String s : new HashSet<>(arr))
System.out.println("element: " + s
+ ", count: " + Collections.frequency(arr, s));
Output: same. But note that this might result in different order of the output as Set
s in Java are not ordered.
I would work with a HashMap, whereas the meaning is element -> count! pseudo:
HashMap<Integer, Integer> counts = new HashMap<Integer, Integer>();
for(int i=0; i<arr.size(); ++i){
Integer x = counts.get(arr.get(i));
if (x==null) counts.put(arr.get(i), 1);
else counts.put(arr.get(i), x+1);
}
after this, your hashmap holds all elements and their count
try this
List a = Arrays.asList(1, 2, 1, 3, 1);
Collections.sort(a);
Object o = a.get(0);
int n = 1;
for (int i = 1; i < a.size(); i++) {
Object t = a.get(i);
if (o.equals(t)) {
n++;
} else {
System.out.println(o + " - " + n);
n = 1;
o = t;
}
}
System.out.println(o + " - " + n);
output
1 - 3
2 - 1
3 - 1
快速,聪明的方法是:1)使用Collections.sort对arrayList进行排序2)使用indexOf()获取第一个索引,并使用lastIndexOf()方法获取最后一个索引3)2个索引的差将为您提供出现次数给定对象在ArrayList中。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.