Group multiple occurrence of array elements ordered by first occurrence | Java program to group multiple occurrences of individual array elements ; A hashing based method to group all occurrences of individual elements ; Creates an empty hashmap ; Traverse the array elements , and store count for every element in HashMap ; Check if element is already in HashMap ; Increment count of element element in HashMap ; Traverse array again ; Check if this is first occurrence ; If yes , then print the element ' count ' times ; And remove the element from HashMap . ; Driver method to test above method
import java . util . HashMap ; class Main { static void orderedGroup ( int arr [ ] ) { HashMap < Integer , Integer > hM = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { Integer prevCount = hM . get ( arr [ i ] ) ; if ( prevCount == null ) prevCount = 0 ; hM . put ( arr [ i ] , prevCount + 1 ) ; } for ( int i = 0 ; i < arr . length ; i ++ ) { Integer count = hM . get ( arr [ i ] ) ; if ( count != null ) { for ( int j = 0 ; j < count ; j ++ ) System . out . print ( arr [ i ] + " ▁ " ) ; hM . remove ( arr [ i ] ) ; } } } public static void main ( String [ ] args ) { int arr [ ] = { 10 , 5 , 3 , 10 , 10 , 4 , 1 , 3 } ; orderedGroup ( arr ) ; } }