Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,950 questions

51,892 answers

573 users

How to group elements of an array based on their first occurrence in Java

1 Answer

0 votes
import java.util.HashMap;
import java.util.Map;
 
public class MyClass
{
    public static void group_elements(int[] arr) {
        Map<Integer, Integer> frequency = new HashMap<>();
 
        for (int num: arr) {
            frequency.put(num, frequency.getOrDefault(num, 0) + 1);
        }
 
        for (int num: arr) {
            if (frequency.containsKey(num)) {
                int total_frequency = frequency.get(num);
                while (total_frequency-- != 0) {
                    System.out.print(num + " ");
                }
 
                frequency.remove(num);
            }
        }
    }
 
    public static void main(String[] args)
    {
        int[] arr = { 8, 3, 7, 8, 2, 5, 8, 5, 1, 9, 8, 1, 7 };
 
        group_elements(arr);
    }
}




/*
run:

8 8 8 8 3 7 7 2 5 5 1 1 9 

*/

 



answered Aug 14, 2022 by avibootz
...