troubleshooting Question

ArrayList values based on an index allowing duplicates

Avatar of kalyangkm
kalyangkmFlag for United States of America asked on
Java* Arraylist
6 Comments1 Solution11 ViewsLast Modified:
Hi folks,

I am just trying to learn here,
I am trying to get the corresponding reference values into the output based on the index whenever there is a match of iD1 in parent, But its only getting me the first match value.

package test.code.core.Collections;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ArrayListTest {
   
   public static void main(String args[]) {
      try {
         
            String[] parent = new String[] { "", "185", "185", "", "192" };
         String[] iD1 = new String[] { "185", "167", "168", "192", "229" };
         String[] reference = new String[] { "$5", "$1", "$2", "$9", "$10" };
         
         List<String> pID = Arrays.asList(parent);
         List<String> iD = Arrays.asList(iD1);
         List<String> ref = Arrays.asList(reference);
         List<String> out = new ArrayList<String>();
         
         /*for(int i = 0; i<iD.size(); i++) {
            if(pID.contains(iD.get(i))) {
               out.add(ref.get(pID.indexOf(iD.get(i))));
            }
         }*/
         
         
         for(String i : iD) {
            if(pID.contains(i)) {
               out.add(ref.get(pID.indexOf(i)));
            }
         }
          
         System.out.println("The refecence list is :" +out);
      }catch(NullPointerException e) {
         System.out.println("Exception thrown :" +e);
      }
   }

}


So the output I am getting is the following:
The reference list is :[$1, $10]

But what I would need is the following
The reference list is :[$1, $2, $10]
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 6 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 6 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros