Showing posts with label collections. Show all posts
Showing posts with label collections. Show all posts

Saturday, April 27, 2019

what will be the output of the following code?

Problem statement:
What will be the output of the following code?
  1. import java.util.ArrayList;
  2. public class ArrayListExample {
  3.     public static void main(String[] args) {
  4.         ArrayList list = new ArrayList();
  5.         list.add("a");
  6.         list.add("b");
  7.         list.add(1,"c");
  8.         list.add("d");
  9.         list.add(2,"e");
  10.         System.out.println(list);
  11.     }
  12. }
Output: [a, c, e, b, d]

Wednesday, July 25, 2018

What will be the output of the below code?

Problem statement:
What will be the output of the code when we override hashCode() & equals() in java

public class Employee {
    String name;
    int age;
    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((name == null) ? 0 : name.hashCode());
        return result;
    }
    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Employee other = (Employee) obj;
        if (age != other.age)
            return false;
        if (name == null) {
            if (other.name != null)
                return false;
        } else if (!name.equals(other.name))
            return false;
        return true;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}
import java.util.HashMap;
import java.util.Map;

public class HashMapMain {
    public static void main(String[] args) {
        Employee emp1=new Employee("Vikesh",21);
        Map<Employee,String> hm=new HashMap<Employee,String>();
        hm.put(emp1, "Verified");
        System.out.println("11: "+emp1.hashCode());
        emp1.setName("Ishaan");
        System.out.println("22: "+emp1.hashCode());
        System.out.println(hm.get(emp1));
    }
}
Output:
11: -1732600440
22: -2095637962
null

Monday, July 16, 2018

Can you write code for the implementation of Fail Safe Iteration in java?

Problem statement: how do you write code for Fail Safe Iteration in java?
#ConcurrentHashMap:
import java.util.concurrent.ConcurrentHashMap;
import java.util.Iterator;
public class FailSafeExample {
    public static void main(String[] args) {
        // Creating a ConcurrentHashMap        
       ConcurrentHashMap<String, Integer> map
                = new ConcurrentHashMap<String, Integer>();
        map.put("ONE", 1);
        map.put("TWO", 2);
        map.put("THREE", 3);
        map.put("FOUR", 4);
        // Getting an Iterator from map        
       Iterator it = map.keySet().iterator();
        while (it.hasNext()) {
            String key = (String) it.next();
            System.out.println(key + " : " + map.get(key));
            // This will reflect in iterator.            
           // Hence, it has not created separate copy            
           map.put("SEVEN", 7);
        }
    }
}
Output:
ONE : 1
FOUR : 4
TWO : 2
THREE : 3
SEVEN : 7

Can you write code for the implementation of Fail Fast Iteration in java?

Problem statement: how do you write code for Fail Fast Iteration in java?
#HashMap:
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class FailFastExample {
    public static void main(String[] args) {
        Map<String, String> city = new HashMap<String, String>();
        city.put("Bangalore", "India");
        city.put("Tokyo", "Japan");
        city.put("Dubai", "UAE");
        city.put("New Jersey", "USA");

        Iterator iterator = city.keySet().iterator();

        while (iterator.hasNext()) {
            System.out.println(city.get(iterator.next()));
            // adding an element to HashMap exception will be thrown on next 
            // call of next() method.            
            city.put("Istanbul", "Turkey");
        }
    }
}

Output:
Exception in thread "main" java.util.ConcurrentModificationException
Japan
 at java.util.HashMap$HashIterator.nextNode(HashMap.java:1429)
 at java.util.HashMap$KeyIterator.next(HashMap.java:1453)
 at com.com.interview.FailFastExample.main(FailFastExample.java:18)
#ArrayList:
import java.util.ArrayList;
import java.util.Iterator;

public class FailFastExample {
    public static void main(String[] args) {
        ArrayList<Integer> lists = new ArrayList<>();
        lists.add(1);
        lists.add(2);
        lists.add(3);
        lists.add(4);
        lists.add(5);

        Iterator<Integer> itr = lists.iterator();
        while (itr.hasNext()) {
            if (itr.next() == 2) {
                // will not throw Exception

             itr.remove();
            }
        }

        System.out.println(lists);

        itr = lists.iterator();
        while (itr.hasNext()) {
            if (itr.next() == 3) {
                // will throw Exception on next call of next() method
lists.remove(3); } } } } Output: [1, 3, 4, 5] Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901) at java.util.ArrayList$Itr.next(ArrayList.java:851) at com.com.interview.FailFastExample.main(FailFastExample.java:27)

what do you mean by Fail Fast & Fail Safe iterators in java?

Problem statement: what do you mean by Fail Fast & Fail Safe Iterator in java?
Iterators in java are used to iterate over the Collection objects.
Fail-Fast iterators immediately throw ConcurrentModificationException if there is structural modification of the collection. Structural modification means adding, removing or updating any element from collection while a thread is iterating over that collection.

Iterator on ArrayList, HashMap classes are examples of fail-fast Iterator.

Fail-Safe iterators don’t throw any exceptions if a collection is structurally modified while iterating over it. This is because, they operate on the clone of the collection, not on the original collection and that’s why they are called fail-safe iterators. 

Iterator on ConcurrentHashMap, CopyOnWriteArrayList classes are examples of fail-safe Iterator.

2nd Explanations:
A fail-fast system is nothing but immediately report any failure that is likely to lead to failure. When a problem occurs, a fail-fast system fails immediately. In Java, we can find this behavior with iterators

Fail-Safe iterators don't throw any exceptions if the collection is modified while iterating over it. Because, they iterate on the clone of the collection not on the actual collection

Sunday, June 3, 2018

LinkedHashSet

Problem statement: what do you mean by LinkedHashSet in collection?
  1. LinkedHashSet is the child class of HashSet
  2. Introduced in 1.4 version
  3. LinkedHashSet is exactly same as HashSet except the following difference
  • HashSet:
  1. The underlying data structure is Hashtable
  2. Insertion order is not preserved
  3. Introduced in 1.2 version
  • LinkedHashSet:
  1. The underlying data structure is Hash table + Linked List(this is hybrid data structure)
  2. Insertion order is preserved
  3. Introduced in 1.4 version
For example:-
  • HashSet:
  1. import java.util.HashSet;
  2. public class HashSetExe {
  3. public static void main(String[] args) {
  4. HashSet h = new HashSet();
  5. h.add("B");
  6. h.add("C");
  7. h.add("D");
  8. h.add("Z");
  9. h.add("null");
  10. h.add("10");
  11. System.out.println(h.add("z"));
  12. System.out.println(h.add("Z"));
  13. System.out.println(h);
  14. }
  15. }

Output:
true
false
[B, C, D, null, Z, z, 10]

Note: Here, insertion order is not preserved in HashSet

  • LinkedHashSet:
  1. import java.util.LinkedHashSet;
  2. public class LinkedHashSetExe {
  3. public static void main(String[] args) {
  4. LinkedHashSet h = new LinkedHashSet();
  5. h.add("B");
  6. h.add("C");
  7. h.add("D");
  8. h.add("Z");
  9. h.add("null");
  10. h.add("10");
  11. System.out.println(h.add("z"));
  12. System.out.println(h.add("Z"));
  13. System.out.println(h);
  14. }
  15. }
Output:
true
false
[B, C, D, Z, null, 10, z]
Note: Here, insertion order is preserved in LinkedHashSet

  1. LinkedHashSet is the best choice to develop cache based applications, where duplicates are not allowed and insertion order must be preserved.

Saturday, April 28, 2018

Sort a Map by value !!

Sorting a Map by value in Java:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SortMapByValue {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("z", 2);
map.put("q", 0);
map.put("p", 5);
map.put("s", 8);
map.put("o", 0);
map.put("r", 9);
map.put("v", 8);
System.out.println(map);
Set<Entry<String, Integer>> entrySet = map.entrySet();
List<Entry<String, Integer>> lists = new ArrayList<Entry<String, Integer>>(entrySet);

Collections.sort(lists, new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
System.out.println("--------------------");
for (Map.Entry<String, Integer> entry : lists) {
System.out.println(entry.getKey() + " :: " + entry.getValue());
}
}
}

Output:

{p=5, q=0, r=9, s=8, v=8, z=2, o=0}
--------------------
q :: 0
o :: 0
z :: 2
p :: 5
s :: 8
v :: 8
r :: 9

Sort a HashMap by key !!

Sorting a HashMap by key in Java:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class SortMapByKey {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("z", 1);
map.put("q", 2);
map.put("p", 3);
map.put("s", 4);
map.put("o", 5);
System.out.println(map);
Set<Entry<String, Integer>> entrySet = map.entrySet();
List<Entry<String, Integer>> lists = new ArrayList<Entry<String, Integer>>(entrySet);

Collections.sort(lists, new Comparator<Entry<String, Integer>>() {
@Override
public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
return (o1.getKey()).compareTo(o2.getKey());
}
});
System.out.println("--------------------");
for (Map.Entry<String, Integer> entry : lists) {
System.out.println(entry.getKey() + " :: " + entry.getValue());
}
}
}

Output: 
{p=3, q=2, s=4, z=1, o=5}
--------------------
o :: 5
p :: 3
q :: 2
s :: 4
z :: 1

Friday, April 27, 2018

Java sort single field using Comparator.


import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class SortBySalary implements Comparator<Human> {
@Override
public int compare(Human o1, Human o2) {
if (o1.salary > o2.salary)
return 1;
if (o1.salary < o2.salary)
return -1;
return 0;
}

}

class Human {
String name;
int age;
double salary;

public Human(String n, int a, double s) {
this.name = n;
this.age = a;
this.salary = s;
}

public Human() {
}

public String toString() {
return this.name + " " + this.age + " " + this.salary;
}

}

public class ComparatorExe {
public static void main(String[] args) {

List<Human> l = new ArrayList();
Human h1 = new Human("ritesh", 12, 6000);
Human h2 = new Human("raju", 18, 5000);
Human h3 = new Human("ishaan", 10, 7000);
Human h4 = new Human("yuyu", 15, 333);
Human h5 = new Human("yuyu", 17, 333);
Human h6 = new Human("yuyu", 13, 333);
l.add(h1);
l.add(h2);
l.add(h3);
l.add(h4);
l.add(h5);
l.add(h6);

System.out.println(l);

Collections.sort(l, new SortBySalary());
System.out.println(l);
}

}


Output:
[ritesh 12 6000.0, raju 18 5000.0, ishaan 10 7000.0, yuyu 15 333.0, yuyu 17 333.0, yuyu 13 333.0]
[yuyu 15 333.0, yuyu 17 333.0, yuyu 13 333.0, raju 18 5000.0, ritesh 12 6000.0, ishaan 10 7000.0]

Java sort multiple fields using Comparator.

Sort multiple fields using Comparator:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

class SortByAnimalName implements Comparator<Animal> {

@Override
public int compare(Animal o1, Animal o2) {
return o1.name.compareTo(o2.name);
}
}

class SortByAnimalColor implements Comparator<Animal> {

@Override
public int compare(Animal o1, Animal o2) {
return o1.color.compareTo(o2.color);
}
}

class SortByAnimalWeight implements Comparator<Animal> {

@Override
public int compare(Animal o1, Animal o2) {
if (o1.weight > o2.weight) {
return 1;
}
if (o1.weight < o2.weight) {
return -1;
}
return 0;
}
}

class SortByAllAnimal implements Comparator<Animal> {

List<Comparator<Animal>> allFields;

@SafeVarargs
SortByAllAnimal(Comparator<Animal>... allSort) {
this.allFields = Arrays.asList(allSort);

}
@Override
public int compare(Animal o1, Animal o2) {
for (Comparator<Animal> x : allFields) {
int res = x.compare(o1, o2);
if (res != 0) {
return res;
}
}
return 0;
}
}

class Animal {
String color;
String name;
int weight;

Animal(String c, String n, int w) {
this.color = c;
this.name = n;
this.weight = w;
}
@Override
public String toString() {
return this.color + " " + this.name + " " + this.weight;
}
}

public class SortMultipleDataByComparator{
public static void main(String[] args) {
List<Animal> l = new ArrayList<Animal>();
Animal a1 = new Animal("black", "dog", 20);
Animal a2 = new Animal("white", "cat", 15);
Animal a3 = new Animal("black", "elephant", 120);
Animal a4 = new Animal("white", "horse", 80);
l.add(a1);
l.add(a2);
l.add(a3);
l.add(a4);
System.out.println(l);
System.out.println("------------------------------------");
Collections.sort(l,
new SortByAllAnimal(new SortByAnimalColor(), new SortByAnimalName(), new SortByAnimalWeight()));

System.out.println(l);
}
}


Output:

[black dog 20, white cat 15, black elephant 120, white horse 80]
------------------------------------
[black dog 20, black elephant 120, white cat 15, white horse 80]

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...