Reputation: 1
I have two list say 'src' and 'dest'. src contain some duplicates. I need to identify the index of the duplicate elements. After identifying the index, I want to fetch elements from the same index position of the 'dest' list
Upvotes: 0
Views: 2798
Reputation: 1442
import java.util.List;
import java.util.ArrayList;
public class list{
public static void main(String[] args){
List<String> l1 = new ArrayList<String>(10);
List<String> l2 = new ArrayList<String>(10);
l1.add("one");
l1.add("two");
l1.add("three");
l1.add("four");
l1.add("five");
l1.add("six");
l1.add("seven");
l1.add("eight");
l1.add("nine");
l1.add("ten");
l2.add("one");
l2.add("two");
l2.add("three");
l2.add("eight");
l2.add("nine");
l2.add("one");
l2.add("two");
l2.add("three");
l2.add("eight");
l2.add("nine");
List<String> l3 = new ArrayList<String>(10);
for ( int i = 0 ; i < l2.size(); i++){
if( l3.contains(l2.get(i)))
System.out.println(l1.get(i));
else
l3.add(l2.get(i));
}
}
}
This should print out all the strings that are at an index where an item in l2 is repeated. i.e six->10
Upvotes: 1
Reputation: 14178
Here is another solution. The code is not fully complete. The idea is that you create a new array where the values are a new class that contains the values plus their original position. Then you sort src and use the sorted version to find duplicates. When you find one you can then get the position it originally had.
class EntryWithIndex {
private int index;
private Object value;
... constructor, getter, setters ....
}
List<EntryWithIndex> srcWithIndexSaved = new ArrayList<EntryWithIndex>();
int i=0;
for( Object o : src ){
srcWithIndexSaved.add(new EntryWithIndex(i++, o));
}
Collections.sort(srcWithIndexSaved, new Comparator() .... );
for( int i=0; i<srcWithIndexSaved; i++ ){
if( i>0 ){
Object current = srcWithIndexSaved.get(i);
Object previous = srcWithIndexSaved.get(i-1);
if( current.getValue().equals(previous.getValue()) ){
... use current.getIndex() to lookup it up in the dest list.
}
}
}
Upvotes: 0
Reputation: 1108
Here is the algo to do this:
1. Create a HashMap <Integer,List<Integer> > hm = new HashMap <Integer,List<Integer> >();
2. Iterate through the source list and fill this HashMap such that The key is the each number that you see and value will be a list that contains the list of indexes
int counter = 0;
for(Integer number : src){
If(hm.contains(number){
List<Integer> l = hm.get(number);
l.append(counter);
}
else{
List<Integer> l = new List<Integer>();
l.add(counter);
}
}
3. Using these that were stored in Hashmap to (print / fetch) the elements of destination list.
Upvotes: 1