I am trying to write condition in the class if "field1__c is not equal to map1 key value and field2__c is not equal to map1 key value " then it should throw an error.

After assigning when I checked in logs it is storing null value. Can anyone please help me with this.

Class :

List<ABC__C > ABRecords =[select Id,field1__c,field2__c from ABC__C];
Map<String,String> Mapfield1 = new  Map<String,String>();
Map<String,String> Mapfield2 = new  Map<String,String>();

for(ABC__C abRecs: ABRecords) {
    Mapfield2 .put(abRecs.id,abRecs.field2__c );

List<NoteBook__c> notList = [Select Id,field1Notes__c,field2Notes__c , ssp__c,Rating__c from NoteBook__c ];

for(NoteBook__c books: notList) {

    LineItem__c li=new LineItem__C();

    li.Quality= 1;   
    li.price = books.ssp__c;

    System.debug('Mapfield2 val::##' + Mapfield2.get(books.field2Notes__c)); // I am getting null value 

    if((books.field2Notes__c != Mapfield2.get(books.field2Notes__c)) && books.field1Notes__c != Mapfield1.get(books.field1Notes__c)){

        ApexPages.Message errormsg = new ApexPages.Message(ApexPages.severity.ERROR,'Please re-check values');
        return null;
    else if((books.field2Notes__c != Mapfield2.get(books.field2Notes__c)) && books.field1Notes__c != Mapfield1.get(books.field1Notes__c)){
        li. field1Line__c= books.field1Notes__c;
        li.field2Line__c = books.field2Notes__c;

insert listbook;

2 Answers 2


You are creating the maps like these:


Mapfield2 .put(abRecs.id,abRecs.field2__c );

And later using this Mapfield2.get(books.field2Notes__c)value for comparison.

I think books.field2Notes__c which is using as key is not same key as abRecs.id. Thats why it is returning null.

  • I was able to get the ABRecords id if I am using like this Mapfield1.put(abRecs.field1__c,abRecs.id); and Mapfield1.get(books.field1Notes__c)) Instead of Id I want field1__c value that i am not able to get
    – Learner
    Jun 29, 2016 at 13:57

Add the map like id as key and Sobject as value

Map<String,ABC__C> Mapfield1 = new Map<String,ABC__C>();
Map<String,ABC__C> Mapfield2 = new Map<String,ABC__C>();

for(ABC__C abRecs: [select Id,field1__c,field2__c from ABC__C]) 
    Mapfield2.put(abRecs.field2__c,abRecs );

Now you can check the value with eh help of map as like below,

books.field2Notes__c != Mapfield2.get(books.field2Notes__c).Field2__c

Its always prefer to check the null point and then use the map.get() values.

Keep somthing like below,

 if(Mapfield2.get(books.field2Notes__c) != null && Mapfield1.get(books.field1Notes__c) != null && 
(books.field2Notes__c != Mapfield2.get(books.field2Notes__c).Field2__c ) && books.field1Notes__c != Mapfield1.get(books.field1Notes__c).field1__c)
           //Do stuff

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .