这个问题是要在一个数组中计算有多少个1、2和3。
Java 7的解决方案如下:
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class howMany1 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765);
Map<Integer ,Integer> map = new HashMap<>();
for( Integer r : list) {
if( map.containsKey(r) ) {
map.put(r, map.get(r) + 1);
}
else {
map.put(r, 1);
}
}
Set< Map.Entry<Integer ,Integer> > entrySet = map.entrySet();
for( Map.Entry<Integer ,Integer> entry : entrySet ) {
System.out.printf( "%s : %d %n " , entry.getKey(),entry.getValue() );
}
}}
在Java 8中,解决问题的方法是:
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
public class howMany2 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181, 6765);
Map<Integer ,Long > map = list.stream()
.collect( Collectors.groupingBy(c ->c , Collectors.counting()) ) ;
map.forEach( (k , v ) -> System.out.println( k + " : "+ v ) );
}}
另一种方法是使用Collections.frequency。解决方案如下:
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class Duplicates1 {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 1, 2, 3, 5, 8, 13,13, 21, 34, 55, 89, 144, 233);
System.out.println("Count all with frequency");
Set<Integer> set = new HashSet<Integer>(list);
for (Integer r : set) {
System.out.println(r + ": " + Collections.frequency(list, r));
}
}}
另一种方法是使用方法=> Arrays.stream(array).boxed().collect(Collectors.toList()) 将int数组转换为Integer列表,然后使用for循环获取整数。
public class t7 {
public static void main(String[] args) {
int[] a = { 1, 1, 2, 3, 5, 8, 13, 13 };
List<Integer> list = Arrays.stream(a).boxed().collect(Collectors.toList());
for (Integer ch : list) {
System.out.println(ch + " : " + Collections.frequency(list, ch));
}
}
}