Sunday, 12 January 2020

Interview Question for Java, Advance Java, Spring

Interview Question from top company in this days.

In interview mostly people concentrate on the collections.
This days people are asking like logical and theoretical questions. You should be prefect in the theoretical 

1. Write program for removing the duplicate values from the list without using the collections

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

/**
 * @author DGuntha
 *
 */
public class RemoveDuplicate {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Test");
list.add("Java");
list.add("test1");
list.add("Java");
list.add("Java1");
list.add("Java");
list.add("1");
list.add("2");
list.add("1");
for (int i=0; i < list.size(); i++) {
for (int j=i+1;j<list.size();j++) {
if (list.get(i) == list.get(j)) {
list.remove(j);
}
}
}
list.stream().forEach(s -> System.out.println(s));
}

}

2.Using the collection how to remove the duplicates from the list?
Answer: You can added all the value in to the LinkedHashSet from the list 
public static void removeDuplicatesFromList(List<String> list) {
Set<String> set = new LinkedHashSet<String>();
set.addAll(list);
list.clear();
list.addAll(set);
list.parallelStream().forEach(s -> System.out.println(s));
}
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("Test");
list.add("Java");
list.add("test1");
list.add("Java");
list.add("Java1");
list.add("Java");
list.add("1");
list.add("2");
list.add("1");
removeDuplicatesFromList(list);
}
3. What is ConcurrentModificationException?

ConcurrentModificationException

public class ConcurrentModificationTest {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> myList = new ArrayList<String>();

myList.add("1");
myList.add("2");
myList.add("3");
myList.add("4");
myList.add("5");
myList.add("3");

//If Use the iterator and try to remove the value ConcurrentModification exception occurred
// Because count value of the iterator is stored in the abstract class.
Iterator<String> itorator = myList.iterator();
while (itorator.hasNext()) {
String value = itorator.next();
System.out.println("List value : "+value);
if (value.equals("3")) {
myList.remove(2);
}
}
// This will not provide the ConcurrentModification exception because we are moving the list.
for (int i = 0; i< myList.size(); i++) {
if (myList.get(i).equals("3")) {
myList.remove(3);
}
}

}

}


what is stream map in java?