In: Computer Science
You are given a List L of generic type <T> , and another List P, which contains integers sorted in ascending order. The operation printLots(L,P) will print the elements in L that are in positions specified by P. For instance, if P = [1,3,4,6], the elements in positions 1,3,4, and 6 in L are printed. Write the procedure printLots(L,P). The code you provide should be the Java method itself (not pseudocode), the containing class is not necessary. You may use only use public Collection method that is inherited by Lists L and P, with the exception of the toArray() method. You may assume that the any integer in P is greater than or equal to 0 and less than L.size(). Both L and P can be empty. (Note: this is an iterator question, your solution must use iterators on L and P.)
import java.util.*;
public class PrintMessage{
public static void main (String[] args) {
Scanner sc=new Scanner(System.in);
List<Integer> L=new ArrayList<Integer>();
L.add(5);
L.add(4);
L.add(6);
L.add(7);
L.add(9);
L.add(2);
List<Integer> P=new ArrayList<Integer>();
P.add(1);
P.add(4);
P.add(5);
P.add(2);
System.out.println("Elements in L are:");
for (int i=0;i<L.size();i++){
System.out.print(L.get(i)+" ");
}
System.out.println("\nElements in P are:");
for (int i=0;i<P.size();i++){
System.out.print(P.get(i)+" ");
}
PrintMessage obj=new PrintMessage();
obj.printLots(L,P);
}
public void printLots(List<Integer> L,List<Integer> P){
List<Integer> result=new ArrayList<Integer>();
for (int i=0;i<P.size();i++){
result.add(L.get(P.get(i)));
}
System.out.println("\nResult:");
for(int i=0;i<result.size();i++){
System.out.print(result.get(i)+" ");
}
}
}
Thank you!, if you have any queries post it below in the comment section i will try my best to resolve your queries and i will add it to my answer if required. Please give upvote if you like it.