[英]Java count all the values of an array and store it in an array
我想計算一個數組的值並將其保存在一個數組中。在php中,我們使用array_count_values進行計數。
$a=array("A","Cat","Dog","A","Dog");
print_r(array_count_values($a));
輸出:
Array ( [A] => 2 [Cat] => 1 [Dog] => 2 )
我想在Java中這樣做。
Map<String, String[]> map = request.getParameterMap();
String[] wfBlockIds = map.get("wf_block_id[]");
Arrays.stream(wfBlockIds)
.collect(Collectors.groupingBy(s -> s))
.forEach((k, v) -> System.out.println(k+" => "+v.size() + " --" + v));
Java代碼的輸出為:
1469441140125 => 3 --[1469441140125, 1469441140125, 1469441140125]
1469441126299 => 2 --[1469441126299, 1469441126299]
我將如何獲得與array_count_values()等效的結果,該結果將在數組中。
嘗試以下代碼:
Map<String, Integer> map = new HashMap<>();
for (String s : array) {
if (map.containsKey(s)) {
Integer v = map.get(s);
map.put(s, v+1);
} else {
map.put(s, 1);
}
}
盡管Java數組僅具有int索引,但您可以實現與PHP與Map相同的功能。
以下代碼產生類似於array_count_values
Map<String, Long> result = Stream.of("A", "Cat", "Dog", "A", "Dog")
.collect(groupingBy(Function.identity(), counting()));
System.out.println(result); //prints {A=2, Cat=1, Dog=2}
您的代碼很好,但是從請求參數中獲取的String數組包含3 *“ 1469441126299”和2 *“ 1469441140125”; 打印出您的request.getParameterMap(),您將看到
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.