Manoj Kumar Manoj Kumar - 11 days ago 11
Android Question

search sub list into another list in android

For example there are two lists(Array List) A and B .
Length(size) of A is 10 and Length(size) is 100 .
All the items of A exists in B. I want to get index position in B which is in A.

A[
{
id = 10, name = "a"
},
{
id = 22, name = "b"
},
{
id = 30, name = "c"
},
{
id = 45, name = "d"
},
{
id = 55, name = "e"
},
...
]

B[
{
id = 1, name = "xx"
},
{
id = 2, name = "yy"
},
...
{
id = 10, name = "a"
},
{
id = 11, name = "zz"
},
...
{
id = 22, name = "b"
},
...,
{
id = 100, name = "hello"
}
]


I want to index position A item in B. I am using two for loops. But it is taking time.
If there are any way to search these items using one for loop or any other way.

Answer

You can use a HashMap to store the larger array of the two. This way, you only have to iterate through the smaller array, checking if the current object exists in the hash map in O(1), which gives you a total complexity of O(n), where n is the dimension of the smaller array.