Generally it is better to let the database do the counting rather than pulling the data out and then looping over it. That also allows the results to be easily ordered.
Using that approach, and (as in guy's example assuming you just want separate lists - not so good otherwise) the code would look like this:
public with sharing class MyController {
public AggregateResult[] accounts {
get {
if (accounts == null) {
accounts = [
select Name n, count(Id) c
from Account
group by Name
order by Name
limit 10000
];
}
return accounts;
}
private set;
}
public AggregateResult[] contacts {
get {
if (contacts == null) {
contacts = [
select Name n, count(Id) c
from Contact
group by Name
order by Name
limit 10000
];
}
return contacts;
}
private set;
}
}
and the Visualforce like this:
<apex:page controller="MyController">
<apex:pageblock title="Accounts">
<apex:pageBlockTable value="{!accounts}" var="ar">
<apex:column headerValue="Account Name">
{!ar['n']}
</apex:column>
<apex:column headerValue="Duplicate Count">
{!ar['c']}
</apex:column>
</apex:pageBlockTable>
</apex:pageblock>
<apex:pageblock title="Contacts">
<apex:pageBlockTable value="{!contacts}" var="ar">
<apex:column headerValue="Contact Name">
{!ar['n']}
</apex:column>
<apex:column headerValue="Duplicate Count">
{!ar['c']}
</apex:column>
</apex:pageBlockTable>
</apex:pageblock>
</apex:page>
and PS a controller test:
@isTest
private class MyControllerTest {
@isTest
static void test() {
Account[] accounts = new Account[] {
new Account(Name = 'Acme'),
new Account(Name = 'Acme'),
new Account(Name = 'Zebra')
};
insert accounts;
Contact[] contacts = new Contact[] {
new Contact(LastName = 'Smith', AccountId = accounts[0].Id),
new Contact(LastName = 'Jones', AccountId = accounts[1].Id),
new Contact(LastName = 'Jones', AccountId = accounts[2].Id)
};
insert contacts;
MyController controller = new MyController();
System.assertEquals(2, controller.accounts.size());
System.assertEquals('Acme', controller.accounts[0].get('n'));
System.assertEquals(2, controller.accounts[0].get('c'));
System.assertEquals('Zebra', controller.accounts[1].get('n'));
System.assertEquals(1, controller.accounts[1].get('c'));
System.assertEquals(2, controller.contacts.size());
System.assertEquals('Jones', controller.contacts[0].get('n'));
System.assertEquals(2, controller.contacts[0].get('c'));
System.assertEquals('Smith', controller.contacts[1].get('n'));
System.assertEquals(1, controller.contacts[1].get('c'));
}
}