function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
chaitanyakuamar Teruchaitanyakuamar Teru 

apex list compare


Q.Print and count the unique values from firstColorList, secondColorList  along with the exact count. (red-2,blue-3,yellow-1,black-1,green-1) and ovral count 6

list<String> firstcolourlist=new list<String>{'red','blue','yellow','orange'};
        list<String>secondcolourlist=new list<String{'blue','black','yellow','green','blue'};
           
ANUTEJANUTEJ (Salesforce Developers) 
Hi Chaitanya,

I tried this below sample code and it worked for me can you try checking and modify it as per your scenario:
 
list<String> list1 = new list<String>();
list<String> list2 = new list<String>();
Map<String, integer> mapString= new Map<String, Integer>();
list1.add('a');
list1.add('b');
list1.add('c');
for (String st : list1) {
    mapString.put(st,1);
}
list2.add('d');
list2.add('e');
list2.add('a');
list2.add('b');
for(String st: list2)
{
    if(mapString.containsKey(st))
    {
        Integer count= mapString.get(st)+1;
        mapString.put(st,count); 
    }
    else
    {
        mapString.put(st,1);
    }
}
System.debug(mapString);

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.
chaitanyakuamar Teruchaitanyakuamar Teru
Tq Anujet.
#thanks for your respons.
along with that, I need the total count of all values from list1&list2 count = ' '; 
list 1 = a,b,c,d
list2 = c,a,d,e
total count = 8;
can you help me pls
ANUTEJANUTEJ (Salesforce Developers) 
I used this try checking if this works:
 
Integer totCount = 0;
list<String> list1 = new list<String>();
list<String> list2 = new list<String>();
Map<String, integer> mapString= new Map<String, Integer>();
mapString.put('Total',0);
list1.add('a');
list1.add('b');
list1.add('c');
for (String st : list1) {
    mapString.put(st,1);
    totCount = mapString.get('Total') + 1;
    mapString.put('Total',totCount);
}
list2.add('d');
list2.add('e');
list2.add('a');
list2.add('b');
for(String st: list2)
{
    if(mapString.containsKey(st))
    {
        Integer count= mapString.get(st)+1;
        mapString.put(st,count); 
        totCount = mapString.get('Total') + 1;
        mapString.put('Total',totCount);
    }
    else
    {
        mapString.put(st,1);
        totCount = mapString.get('Total') + 1;
        mapString.put('Total',totCount);
    }
}
System.debug(mapString);