If i understand it correctly then you can use following code:
List<String> code = new List<String>(); Boolean ErrorFlag = flase; List<Object__c> ObjList = [Slect Id,Name,Codes__c from Object__c]; for(Object__c ob : ObjList ) { code.add(ob.Codes__c); } //here i want to write logic If(code.size() > 0){ String first = code[0]; for(String next: code){ if(first != next) ErrorFlag = true; } } if(ErrorFlag){ ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Error'); }
EDIT: If you really need optimized solution for this specific problem defined above then i would do something like this:
list<AggregateResult> result = [select name, count(id) from account group by name having count(id) >1]; if(result.size() > 0){ System.debug('>>> There is error'); }else{ System.debug('>>> No error!'); }
When i check it with developer console analysis it took 15.42 milliseconds and heap used was 1430.

When I run code provided by Adrian Larson it took 21.69 milliseconds & heap used was 60732. 
PS: Following points need to to be considered
1) The index on the column will affect the performance
2) You may not be able to use result variable for showing data for example rendering table with row details
3) The result may vary depending on your schema and number of records