Youtube User
Youtube User

Reputation: 11

Find count of duplicate elements and create arrays of them

i have a list of elements in array like [121,122,121,122,123,121,122] output should be arrays of all the duplicate elements like

[121,121,121]
[122,122,122]
[123]

I am limited to use Java 1.4. This is going to be our last release in this version, the app runs on SAP J2EE server which supports only 1.4.

see the complete code from hint of @Subhrajyoti Majumder

the size prints 9 but when i iterate it is printing too many.. The output should be as following based on delivery number

[a1,a2]
[a3,a4]
[a6]
[a7,a8,a9,a10]

Thanks in advance.

Upvotes: 0

Views: 1446

Answers (1)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41200

Irrespective of your solution if I understood your question correctly then your input would be a array (which contains duplicates) and output would be list of duplicate arrays. I have simple approch towards this problem that is a Map where Integer would be the key and List would be the value. Written a little snippet(java 1.4 supported) below.

Map map = new HashMap();
int[] array = {121,122,121,122,123,121,122};
for(int i=0;i<array.length;i++){
    if(map.get(array[i])==null){ // no entry available
         List list = new ArrayList();
         list.add(array[i]);
         map.put(array[i],list);
    }else // entry is already available
       map.get(array[i]).add(array[i]);
}

I know you have constraint with java version though this could be easier with google collection library - guava's MultiSet. Library is for Java 1.6+.

Snippet -

Multiset<Inetger> multiSet = HashMultiset.create();
int[] array = {121,122,121,122,123,121,122};
multiSet.addAll(Arrays.asList(array));
for (Inetger i : multiSet.elementSet()) {
    System.out.println(i + ": " + multiSet.count(i));
}

Upvotes: 3

Related Questions