0

I want to count values of an array and keep it into an array.In php we do so using array_count_values.

    $a=array("A","Cat","Dog","A","Dog");
    print_r(array_count_values($a));

Output :

    Array ( [A] => 2 [Cat] => 1 [Dog] => 2 )

I want to do so in 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));

Output of the Java Code is :

1469441140125 => 3 --[1469441140125, 1469441140125, 1469441140125]
1469441126299 => 2 --[1469441126299, 1469441126299]

How can I will get equivalent result as array_count_values() which will be in an array.

4
  • What do you want the output type to be? An array of what? Commented Jul 25, 2016 at 10:32
  • output will be an array that will contain element of wfBlockIds array.Array ( [A] => 2 [Cat] => 1 [Dog] => 2 ) Commented Jul 25, 2016 at 10:35
  • 1
    Please update your question instead of putting infos in comments. Commented Jul 25, 2016 at 10:36
  • Arrays in Java can only have int indices, so what you are requesting is not possible, perhaps a Map<String,Integer> will work for you. Commented Jul 25, 2016 at 10:37

3 Answers 3

2

Try the following code:

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Altough Java arrays only have int indices, you can achieve the same functionnality as in PHP with a Map.

The following code produces something similar to 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}

Comments

0

Your code is fine, but the String array that you are getting from request params contains 3 * "1469441126299" and 2 * "1469441140125"; Print out your request.getParameterMap() and you will see that

1 Comment

try to use request.getParameter("wf_block_id[]") without calling the parameterMap

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.