Sample Code:
public class Utility {
public static Map < Integer, List < SObject > > constructFieldCountListSObjs( List < SObject > listSObjs ) {
Map < Integer, List < SObject > > mapFieldCountSObjList = new Map < Integer, List < SObject > >();
for ( SObject obj : listSObjs ) {
String JSONContent = JSON.serialize( obj );
JSONParser parser = JSON.createParser( JSONContent );
Integer intCount = 0;
while ( parser.nextToken() != null ) {
/* Ignoring Start and End Objects */
if ( parser.getCurrentToken() != JSONToken.START_OBJECT
&& parser.getCurrentToken() != JSONToken.END_OBJECT ) {
/* Ignoring attributes and it related contents like type and url.
Ignoring Id and it value.
*/
if ( parser.getCurrentName() == ‘attributes’ ) {
parser.nextToken();
parser.nextToken();
parser.nextToken();
parser.nextToken();
parser.nextToken();
parser.nextToken();
continue;
} else if ( parser.getCurrentName() == ‘Id’ ) {
parser.nextToken();
continue;
}
intCount += 1;
parser.nextToken();
}
}
if ( !mapFieldCountSObjList.containsKey( intcount ) )
mapFieldCountSObjList.put( intcount, new List < Account >() );
mapFieldCountSObjList.get( intcount ).add( obj );
}
return mapFieldCountSObjList;
}
}
Output:
List < Account > listAccs = [ SELECT Name, Industry, Site, AccountSource, AnnualRevenue, Phone, Rating FROM Account LIMIT 10 ];
Map < Integer, List < SObject > > mapFieldCountSObjList = Utility.constructFieldCountListSObjs( listAccs );
for ( Integer i : mapFieldCountSObjList.keySet() ) {
System.debug( ‘Field Count is ‘ + i );
for ( SObject acc: mapFieldCountSObjList.get( i ) ) {
System.debug( ‘Account is ‘ + JSON.serialize( acc ) );
}
}
To print the values in sorted order.
List < Account > listAccs = [ SELECT Name, Industry, Site, AccountSource, AnnualRevenue, Phone, Rating FROM Account LIMIT 10 ];
Map < Integer, List < SObject > > mapFieldCountSObjList = Utility.constructFieldCountListSObjs( listAccs );
List < Integer > listKeys = new List < Integer >();
listKeys.addAll( mapFieldCountSObjList.keySet() );
listKeys.sort();
for ( Integer i : listKeys ) {
System.debug( ‘Field Count is ‘ + i );
for ( SObject acc: mapFieldCountSObjList.get( i ) ) {
System.debug( ‘Account is ‘ + JSON.serialize( acc ) );
}
}