简体   繁体   中英

how can I find a specific value in a arraylist?

I have a list of a list that I'm being passed over as data. The example they gave was the object will look like this:

List assetClassCorrelationMatrix = new ArrayList();
List m1 = new ArrayList();
m1.add(2);
m1.add(4);
m1.add(0.8979);
assetClassCorrelationMatrix.add(m1);

EDIT: OK, so I'm sorry I was not clear. I was thinking that this was going to be in the structure of

correlation[2][4] = 0.8979

Instead they are giving me:

correlation[0] = 2;
correlation[1] = 4;
correlation[2] = 0.8979;

I just need to get back whatever is in correlation[2] when I just have the values of what is in correlation[0] and correlation[1]

Help?

You don't need other values for finding a specific value in nested arraylist. If you are looking for a specific value in arraylist assetClassCorrelationMatrix , you can do this way:

double num = 0.8979;        
for (Object object: assetClassCorrelationMatrix) {            
    List list = (List) object;                                    
    if(list.contains(num))
        System.out.println("The number " + num + " is found at index =  " + list.indexOf(num));
}

Edit: After you edited question, it seems radical change of context. Now you have two value (like index value 2 and 4 in 2D array) and you want to get the value of the index. You could do this using 2D array easily. But if you want to stick with list, you could go this way:

    List assetClassCorrelationMatrix = new ArrayList();

    int a=2, b=4;

    List m1 = new ArrayList();
    List m2 = new ArrayList();        

    // inserting values
    m2.add(0, 1.1); 
    m2.add(1, 2.0);
    m2.add(2, 0.5);
    m2.add(3, 0.8979);

    assetClassCorrelationMatrix.add(m1);
    assetClassCorrelationMatrix.add(m2);

    List list = (List) assetClassCorrelationMatrix.get(a-1);
    Number number = (Number) list.get(b-1);
    System.out.println("List = " + a + " and index = " + b + " and the number = " + number);

Start by specifying properly the type of your lists, it should be something like this:

List<List<Number>> assetClassCorrelationMatrix = new ArrayList<>();
List<Number> m1 = new ArrayList<>();

Then you can access to your value 0.8979 using List#get(int) , like this:

Number n = m1.get(2); // The indexes start from 0, so the index of the 3th element is 2

If you want to access it from assetClassCorrelationMatrix , it would be:

Number n = assetClassCorrelationMatrix.get(0).get(2);

You can identify this value among the other by checking the type, indeed 2 and 4 will be converted automatically as Integer due to auto-boxing and 0.8979 as Double .

for (Number n : m1) {
    if (n instanceof Double) {
        // Here is the code that treats the Double value
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM