http://cognify2-hub.revelian.com/ads/adcc3ee0-8d7e-408a-8cc4-635f906b65cc
J
Difference between map and flat map
Stream and parllelstream,
Caching
Heapspace how to find heapspace error,
Map.remove,
Synchronization locks
Kafka consumer exceptions,
Why functional interface.
Overriding and overloading with exceptions
J
Difference between map and flat map
Stream and parllelstream,
Caching
Heapspace how to find heapspace error,
Map.remove,
Synchronization locks
Kafka consumer exceptions,
Why functional interface.
Overriding and overloading with exceptions
sonar issues,
team leader responsbilities
Hash Map get or retreive operations.
team leader responsbilities
Hash Map get or retreive operations.
What type of challenges are faced in development time/real time in ...
tech prime-->microservie videos
why string is immutbale and
practive in note boook all singlton, immutbale and microservicds.
hibernate and spring scopes and and desing patterns
compare null with null in hashset key
iterator vs streams
why string is immutable
Since Strings are very popular as HashMap key, it's important for them to be immutable so that they can retrieve the value object which was stored in HashMap
Read more: https://javarevisited.blogspot.com/2010/10/why-string-is-immutable-or-final-in-java.html#ixzz6GmB34IS9
Since String is immutable it can safely share between many threads which is very important for multithreaded programming and to avoid any synchronization issues in Java, Immutability also makes String instance thread-safe in Java, means you don't need to synchronize String operation externally.
Another reason of Why String is immutable in Java is to allow String to cache its hashcode, being immutable String in Java caches its hashcode, and do not calculate every time we call hashcode method of String, which makes it very fast as hashmap key to be used in hashmap in Java.
Security and String pool being primary reason of making String immutable
JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent.
jvm provides run time env to execute byte code. not physically
JRE--> jvm+libraries ->physically
Memory managment. https://www.youtube.com/watch?v=ZBJ0u9MaKtM
Class Area/Method Area: metadata of class,static varaibles, byte code, class level constant pool
Bootstrap class loader(rt.jar)
Extension class loader(jre/lib/ext)
Application class loader (classpath,-cp)
Heap area: Objects, arrays because objects.
PC register, pointer to executr next instruction to be .
Stack : stack frame thread method,parameters, return vaue, local varaibles,
Native method statck for native mehtods, method or instacne implementaiton done in antoher language, for example in c languare.
default: with in package,
protected : with in package and subclasses of other packages
private with in class,
public. every where.
Method overriding,
subclass should overide the parent clas mehtod for specific implementaion and should have is a releation shipt, icici(subclass) is abank(parent)
Why we need wrapper class []
Why we need wrapper class []
Java is an object-oriented language and can view everything as an object. A simple file can be treated as an object , an address of a system can be seen as an object , an image can be treated as an object (with java.awt.Image) and a simple data type can be converted into an object (with wrapper classes). This tutorial discusses wrapper classes. Wrapper classes are used to convert any data type into an object.
The primitive data types are not objects; they do not belong to any class; they are defined in the language itself. Sometimes, it is required to convert data types into objects in Java language. For example, upto JDK1.4, the data structures accept only objects to store.
Object class: multilvel inhertiance.
class xyz (extends Object){
}
class abc extends class xyz{
}
explanation: As soon as class abc extends class xyz, now class abc no more extending Object class directly, but class abc is inheriting Object class indirectly via class xyz. So this kind of inheritance is called multi level inheritance.
How many Ways to Create an Object in Java
There are 5 different ways to create object in java:
1. new operator
2. Class.newInstance()
3.newInstance() of constructor of reflection
4.Object.clone () method
5.Java Object serialization and deserialization
2. class A{
String a =hello";
psvm(string arsgs[]){
try{
A obj = A.class.newInstance();
syso(obj.a)
}
3 import java.lang.reflect.Constructor
class A{
String a="hello";
psvm(String args[]){
Constructor<A> obj = A.class.getConstructor()
A a = obj.newInstance();
}
4. clone() defined in Object class
1.Cloneble interface must be implement while using clone() method. defined in lang package.
2.clone() method must be overridden with other classes.
3. When we use clone() method in class, the class must call super.clone() method to get the reference of cloned object.
public class ClonableExample implements Clonable{
protected Object clone() throws CloneNotSupportedException{
return super.clone();
}
psvm(){
ClonableExample obj1 = new ClonableExample();
try{
ClonableExampel obj2 = (ClonableExample)obj1.clone();
}
}
5. Serializable java.io pacakge-->Marker interface
writeObject() method of ObjectOutputStream class is used to serialize an object . The serilization is process of converting an object into sequence of bytes.
The process of creating object from sequence of bytes is called Deserialization. the readObject() method of ObjectInputStream class is used
class Demo implements Serializable{
public int i;
public String s;
publi Demo(int i, String s){
this.i=i;
this.s=s;
}
}
public class DeserializableExample{
psvm(){
Demo demoObject = new Demo(8,"abc");
String fileName ="serializablFile.ser";\\ must be .ser exten
try{
FileOutputStream fos = new FileOutpuStream(fileName);
ObjectOutputStream outStream = new ObjectOutputStream(fos);
outStream.writeObject(demoObject);
outStem.close;
fos.close();
catch()
try{
FileInputStream fis = new FileINputStream(fileName);
ObjectINputStream readStream= new ObjecinputStream(fis);
Demo outObjct = (Demo)readStream.readObject();
radstream.close()
fis.close();
}catch
}
}
String (immutabel) synchronzied
- String s1="Welcome";
- String s2="Welco
String Buffer(mutable)
Java StringBuilder (same as String Buffer except it is non-synchronized)
Collections:
ArrayList:
Dynamic array to store elements,can duplicates, maintain insertion order, non synchronized, random access bec index basis.
manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list.
Vector:
Synchronzied
ArrayList
|
Vector
|
---|---|
1) ArrayList is not synchronized.
|
Vector is synchronized.
|
2) ArrayList increments 50% of current array size if the number of elements exceeds from its capacity.
|
Vector increments 100% means doubles the array size if the total number of elements exceeds than its capacity.
|
3) ArrayList is not a legacy class. It is introduced in JDK 1.2.
|
Vector is a legacy class.
|
4) ArrayList is fast because it is non-synchronized.
|
Vector is slow because it is synchronized, i.e., in a multithreading environment, it holds the other threads in runnable or non-runnable state until current thread releases the lock of the object.
|
5) ArrayList uses the Iterator interface to traverse the elements.
|
A Vector can use the Iterator interface or Enumeration interface to traverse the elements.
|
Linked List:
uses a doubly linked list to store the elements,dupliacte, non-sync and maintain insertion order.
In Java LinkedList class, manipulation is fast because no shifting needs to occur.
can act as a list and queue both because it implements List and Deque interfaces.
HashSet:
HashSet stores the elements by using a mechanism called hashing.
unique elements
allows null value, non-sync
ashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
best approach for search operations.
The initial default capacity of HashSet is 16, and the load factor is 0.75.
LinkedHashset:
unique,non-sync,maintains insertion order.permits null elements.maintains insertion order.
TreeSet:
access and retrieval times are quiet fast,does not allow null elements,non-sync, ascending order.
HashMap:
uniquekeys,
may have one null key and multiple null values,non-sync, no order,
The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
LinkedHashMap maintains insertion order, except this same as HashMap.
TreeMap:
unique elements,TreeMap cannot have a null key but can have multiple null values,non-synch, asscending order.
HashTable:
- Java Hashtable class is synchronized.
- The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
HashMap
|
Hashtable
|
---|---|
1) HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.
|
Hashtable is synchronized. It is thread-safe and can be shared with many threads.
|
2) HashMap allows one null key and multiple null values.
|
Hashtable doesn't allow any null key or value.
|
3) HashMap is a new class introduced in JDK 1.2.
|
Hashtable is a legacy class.
|
4) HashMap is fast.
|
Hashtable is slow.
|
5) We can make the HashMap as synchronized by calling this code
Map m = Collections.synchronizedMap(hashMap);
|
Hashtable is internally synchronized and can't be unsynchronized.
|
6) HashMap is traversed by Iterator.
|
Hashtable is traversed by Enumerator and Iterator.
|
7) Iterator in HashMap is fail-fast.
|
Enumerator in Hashtable is not fail-fast.
|
8) HashMap inherits AbstractMap class.
|
Hashtable inherits Dictionary class.
|
Comparable:
java.lang package
java.lang package
to sort userdefined object.
compareTo(Object)
this.no>obj.no returns +
this.no<obj.no returns -
this.no==obj.no returns 0
public int compareTo(Employee emp) {
//let's sort the employee based on an id in ascending order
//returns a negative integer, zero, or a positive integer as this employee id
//is less than, equal to, or greater than the specified object.
return (this.id - emp.id);
}
public int compareTo(Employee emp) {
//let's sort the employee based on an id in ascending order
//returns a negative integer, zero, or a positive integer as this employee id
//is less than, equal to, or greater than the specified object.
return (this.id - emp.id);
}
Comparator:
java.util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).
=============
public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return (int) (e1.getSalary() - e2.getSalary());
}
};
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
=============
public static Comparator<Employee> SalaryComparator = new Comparator<Employee>() {
@Override
public int compare(Employee e1, Employee e2) {
return (int) (e1.getSalary() - e2.getSalary());
}
};
@Override
public int compare(Employee e1, Employee e2) {
return e1.getName().compareTo(e2.getName());
}
abstarct vs interface :
Try with resource
try(FileINputSrema sfis = new Fileinputstra(file)){--> means closes the resource when ever it is used.
} No need to write catch and can have catch ,finally also.
ConcurrentHashmp :
gives performance, by applying lock on only portion of map i.e single segment instead of toatl map. while iterating the concurenthashmpa we can add element but in hashmap we can't it wil throw concurenthashnpa.'
gives performance, by applying lock on only portion of map i.e single segment instead of toatl map. while iterating the concurenthashmpa we can add element but in hashmap we can't it wil throw concurenthashnpa.'
equals method :
Sutudent s1 = new Student("ABC");
Sutudent s2 = new Student("ABC");
nOW they are differnt
but when put into HashMap,
if we override equals method, only one object will return from map.
that is correct.
Immutable class:
public final class FinalClassExample {
private final int id;
private final String name;
private final HashMap<String,String> testMap;
public int getId() {
return id;
}
public String getName() {
return name;
}
// Accessor function for mutable objects
public HashMap<String, String> getTestMap() {
//return testMap;
return (HashMap<String, String>) testMap.clone();
}
/**
* Constructor performing Deep Copy
* @param i
* @param n
* @param hm
*/
public FinalClassExample(int i, String n, HashMap<String,String> hm){
System.out.println("Performing Deep Copy for Object initialization");
this.id=i;
this.name=n;
HashMap<String,String> tempMap=new HashMap<String,String>();
String key;
Iterator<String> it = hm.keySet().iterator();
while(it.hasNext()){
key=it.next();
tempMap.put(key, hm.get(key));
}
this.testMap=tempMap;
}
private final int id;
private final String name;
private final HashMap<String,String> testMap;
public int getId() {
return id;
}
public String getName() {
return name;
}
// Accessor function for mutable objects
public HashMap<String, String> getTestMap() {
//return testMap;
return (HashMap<String, String>) testMap.clone();
}
/**
* Constructor performing Deep Copy
* @param i
* @param n
* @param hm
*/
public FinalClassExample(int i, String n, HashMap<String,String> hm){
System.out.println("Performing Deep Copy for Object initialization");
this.id=i;
this.name=n;
HashMap<String,String> tempMap=new HashMap<String,String>();
String key;
Iterator<String> it = hm.keySet().iterator();
while(it.hasNext()){
key=it.next();
tempMap.put(key, hm.get(key));
}
this.testMap=tempMap;
}
===========
Object cloning:
Shallow coping:
public class Abc{
int i =5;
int j=6;
}
public class Test {
public static void main(String[] args) {
Abc obj = new Abc();
Abc obj1 = obj;--->Shallow coping
obj1.j=10==>here both obj.j and obj1.j are 10
Abc obj2 = new Abc();// Deep cloing
obj2.i=obj.i;// coping manually each and every member.
obj2.j=obj.j;
obj2.j=11;==> here output is 11 but obj.j=10 only
}
============
Cloning.
public class Abc implements Cloneable{
int i =5;
int j=6;
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
Abc obj2 = new Abc();
Obj2.i=6;
Obj2.j=7;
Abc obj3 = (Abc)obj2.clone();// both looks like shallow coping and inernally Deep copying.
obj3.j=12;
}
Concurrent HashMap, and read write locks,
Programs,
*pattern, pyramids programs.
Thread life cycle:
Thread life cycle:
The significant differences between extending Thread class and implementing Runnable interface:
- When we extend Thread class, we can’t extend any other class even we require and When we implement Runnable, we can save a space for our class to extend any other class in future or now.
- When we extend Thread class, each of our thread creates unique object and associate with it. When we implements Runnable, it shares the same object to multiple threads.
2. Difference between Runnable vs Thread
There has been a good amount of debate on which is better way. Well, I also tried to find out and below is my learning.
- Implementing
Runnable
is the preferred way to do it. Here, you’re not really specializing or modifying the thread’s behavior. You’re just giving the thread something to run. That means composition is the better way to go. - Java only supports single inheritance, so you can only extend one class.
- Instantiating an interface gives a cleaner separation between your code and the implementation of threads.
- Implementing
Runnable
makes your class more flexible. If you extendThread
then the action you’re doing is always going to be in a thread. However, if you implementRunnable
it doesn’t have to be. You can run it in a thread, or pass it to some kind of executor service, or just pass it around as a task within a single threaded application.
Thread life cycle, Thread pool, Excecutor framework basics.
3 different ways to create a thread
extending Thread class->java.lang.Thread
implenting RunnableInterface ->java.lang.Runnabel
Implement the java.util.concurrent.Callable interface
3 different ways to create a thread
extending Thread class->java.lang.Thread
implenting RunnableInterface ->java.lang.Runnabel
Implement the java.util.concurrent.Callable interface
class ThreaExample extends Thread{
publiv void run(){
syso();
}
class ThreadTEst{
Thread t = new ThreadExample();
t.start();
}
class RunnableExample implements Runnable{
public void run(){
Syso("runna le example");
}
class rRunnableTEst calss{
psvm(){
ThreadExample obj = new ThreadExample();
Thread t1 = new Thread(obj);
t1.start();
}
}
=========
class Counter implements Callable {
private static final int THREAD_POOL_SIZE = 2;
// method where the thread execution takes place
public String call() {
return Thread.currentThread().getName() + " executing ...";
}
public static void main(String[] args) throws InterruptedException,
ExecutionException {
// create a pool of 2 threads
ExecutorService executor = Executors
.newFixedThreadPool(THREAD_POOL_SIZE);
Future future1 = executor.submit(new Counter());
Future future2 = executor.submit(new Counter());
System.out.println(Thread.currentThread().getName() + " executing ...");
//asynchronously get from the worker threads
System.out.println(future1.get());
System.out.println(future2.get());
}
}
===========
Transient and Volatile
transient
is a Java keyword which marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the javatransient
keyword are not transferred; they are lost intentionally.
Volatile will give the visibility to other threads, many threads can work at a time with out any problem unlike
Synchronization.
It will read from main memory instead of caching value to variable.
JAVA 8
Stream In Java
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
The features of Java stream are –
- A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.
- Streams don’t change the original data structure, they only provide the result as per the pipelined methods.
- Each intermediate operation is lazily executed and returns a stream as a result, hence various intermediate operations can be pipelined. Terminal operations mark the end of the stream and return the result.
Map
List numbers = Arrays.asList(1,3,4,2,6);
List list2 = numbers.stream().map(x->x*2). collect (Collectors.toList);
Filter:
List numbers = Arrays.asList(1,3,4,2,6);
List list2 = numbers.stream() filter(x==1). collect (Collectors.toList)
Sorted:
List numbers = Arrays.asList(1,3,4,2,6);
List list2 = numbers.stream().map(x->x*2). collect (Collectors.toList)
Foreach:
List numbers = Arrays.asList(1,3,4,2,6);
List list2 = numbers.stream().map(x->x*2). collect (Collectors.toList)
Lamda expresssion:
functional interface:
default and static methods definition inside interface,
functional programming.
Stream API:
When working on mutable variable , if multiple threads are working on it, concurrency issues will come,to solve this issues, Stream API come in to picture. helps on Collections and database connections.It helps to achieve concurrency and functional programming.iT focuses on what to do instead of how to do it.
Consumer Interface:
class ConsImple implements Consumer<Integer>{
public void accept(Intger i){
System.out.println(i);
Consuemr consumer// @FunctionalInterface so we can write Lamda expression
}
}
public class DemoForEach{
List<Integer> vlaues = Arrays.asList(4,5,67,8);
values.forEach(i->System.out.println(i));//object of Consumer
Consumer<Integer> c = new ConsImple();
values.forEach(c);//object of Consumer
Wrintg anonymus class
Consumer<Integer> c = /*new Consumer<Integer>(){
public void accept*/(Integer i)-->// noly one mehtod why to write
{
System.out.println(i)
}
;
Consumer<Integer> c = (Integer i)--> System.out.println(i);
values.forEach(c);
Consumer<Integer> c = i--> System.out.println(i);
values.forEach(c);
values.forEach( i--> System.out.println(i));
===================
Steam API:
internal forEach loop by using method reference
List<Integer> values = new ArrayList();
for(int i =0;i<=100;i++){
values.add(i);
}
values.forEach(System.out::println);
values.parallelsteram().forEach(System.out::println);
intermidiate operations :filter(), map()
terminate operations in steam: findFirst(),forEach()
once value is used, we can't resue the valus. ex: we can use the list many times, but steam once
we used, can 't reuse the same, can't print the same again.
LocalDate date = new LocalDate.now();
System.out.println(date);2020-01-13
LocalDate date = new LocalDate.of(2020, 01, 13);
System.out.println(date);2020-01-13
LocalDate date = new LocalDate.of(2020, Month.JANUARY, 13);
===================
java date and time api
java.util.date;
java.sql.date
but now java.time.*
https://www.geeksforgeeks.org/singleton-class-java/
StackOverFlowError.
StackOverFlowError:
The extends the class, which indicates that the JVM is broken, or it has run out of resources and cannot operate. Furthermore, the the extends the class, which is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its clause, because these errors are abnormal conditions that shall never occur.
The extends the class, which indicates that the JVM is broken, or it has run out of resources and cannot operate. Furthermore, the the extends the class, which is used to indicate those serious problems that an application should not catch. A method may not declare such errors in its clause, because these errors are abnormal conditions that shall never occur.
OutOfMemeroyError.
One common indication of a memory leak is the
java.lang.OutOfMemoryError
exception. Usually, this error is thrown when there is insufficient space to allocate an object in the Java heap. In this case, The garbage collector cannot make space available to accommodate a new object, and the heap cannot be expanded further
===
Intervierw preparation
Java:
Why we need wrapper class []
Java is an object-oriented language and can view
everything as an object. A simple file can be treated as an object , an address
of a system can be seen as an object , an image can be treated as an object
(with java.awt.Image) and a simple data type can be converted into an object
(with wrapper classes). This tutorial discusses wrapper classes. Wrapper
classes are used to convert any data type into an object.
The primitive data types are not objects; they do
not belong to any class; they are defined in the language itself. Sometimes, it
is required to convert data types into objects in Java language. For example,
upto JDK1.4, the data structures accept only objects to store.
java 8
Why default methods
For adding lambda expression in Java 8, JDK needs
to add methods(such as foreach) to List or
collections Interface, but if you add this method to these interface, it will
break millions lines of code as class which implements the interface, need to
implement all its methods.
By adding default method in interface, you can
provide default implementation of it without affecting implementing classes.
public interface Decorable {
void
decorateWithCurtains();
default void
decorateWithPaints()
{
System.out.println("Decorate
using paints");
}
}
when you created an interface and many classes
implemented that interface. Now you need to add new methods to interface. After
adding new methods, your java project will be full of compilation errors
because you need to add these new methods to all classes which are implementing
that interface (If a class implement an interface then you have to implement
all its methods in the class).
Both are interfaces.
Iterableà gains ability to iterate over an object of that class using iterator()
internally.
IteratorÃ
An Iterator , on the other hand, is an interface which allows us to iterate over some other object which is a
of some kind. In orderto iterate over an Iterator , we can use hasNext() + next() methods in a while 10
shown below:
Iteraretor iterarotr =Arrays . as List(l
Iterator<lnteger><code>lterator</code>
while (iterator. hasNext()){
System. out. (iterator. next() ) ;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
publicclass IterateOverHashMap {
publicstaticvoidmain(String[] args){
Map<String, Double> employeeSalary =new HashMap<>();
employeeSalary.put("David",76000.00);
employeeSalary.put("John",120000.00);
employeeSalary.put("Mark",95000.00);
employeeSalary.put("Steven",134000.00);
System.out.println("=== Iterating over a HashMap using Java 8 forEach
and lambda ===");
employeeSalary.forEach((employee,
salary)->{
System.out.println(employee
+" =>
"+ salary);
});
System.out.println("\n=== Iterating over the HashMap's entrySet using
iterator() ===");
Set<Map.Entry<String,
Double>> employeeSalaryEntries = employeeSalary.entrySet();
Iterator<Map.Entry<String,
Double>> employeeSalaryIterator = employeeSalaryEntries.iterator();
while(employeeSalaryIterator.hasNext()){
Map.Entry<String, Double>
entry = employeeSalaryIterator.next();
System.out.println(entry.getKey()+" => "+
entry.getValue());
}
System.out.println("\n=== Iterating over the HashMap's entrySet using
Java 8 forEach and lambda ===");
employeeSalary.entrySet().forEach(entry ->{
System.out.println(entry.getKey()+" => "+
entry.getValue());
});
System.out.println("\n=== Iterating over the HashMap's entrySet using
simple for-each loop ===");
for(Map.Entry<String, Double>
entry: employeeSalary.entrySet()){
System.out.println(entry.getKey()+" => "+
entry.getValue());
}
System.out.println("\n=== Iterating over the HashMap's keySet ===");
employeeSalary.keySet().forEach(employee ->{
System.out.println(employee
+" =>
"+ employeeSalary.get(employee));
});
}
}
Equals and hash code contract
if 2 objects are equal by equals method, then has code of 2 objects should be same, but if 2 objects of hash code is same, then not necessary those 2 objects are equal.
=============
https://www.journaldev.com/797/what-is-java-string-pool
why string is immutable.
string object is cacheable in string constant pool,
if there are 50000 students with the same name, istead of creating 50000 times object it creates only one object and refers to that.
and String is very popular as key in hashamp.
=================
=======================
string object is cacheable in string constant pool,
if there are 50000 students with the same name, istead of creating 50000 times object it creates only one object and refers to that.
and String is very popular as key in hashamp.
=================
packagecom.mkyong;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.HashMap;
importjava.util.HashSet;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.TreeMap;
publicclassCountDuplicatedList{
publicstaticvoidmain(String[]args){
List<String>
list =newArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
list.add("b");
list.add("c");
list.add("a");
list.add("a");
list.add("a");
System.out.println("\nExample
1 - Count 'a' with frequency");
System.out.println("a
: "+Collections.frequency(list,"a"));
System.out.println("\nExample
2 - Count all with frequency");
Set<String>uniqueSet=new
HashSet<String>(list);
for(String
temp :uniqueSet){
System.out.println(temp
+": "+Collections.frequency(list,
temp));
}
System.out.println("\nExample
3 - Count all with Map");
Map<String,
Integer> map =new
HashMap<String,
Integer>();
for(String
temp : list){
Integer
count =map.get(temp);
map.put(temp,(count
== null)?1:
count +1);
}
printMap(map);
System.out.println("\nSorted
Map");
Map<String,
Integer>treeMap=newTreeMap<String,
Integer>(map);
printMap(treeMap);
}
publicstaticvoidprintMap(Map<String,
Integer> map){
for(Map.Entry<String,
Integer>entry :map.entrySet()){
System.out.println("Key
: "+entry.getKey()+"
Value : "
+entry.getValue());
}
}
}
Copy
Output
Example 1 - Count 'a'
with frequency
a : 4
Example 2 - Count all with frequency
d: 1
b: 2
c: 2
a: 4
Example 3 - Count all with Map
Key : d Value :
1
Key : b Value :
2
Key : c Value :
2
Key : a Value :
4
Sorted Map
Key : a Value :
4
Key : b Value :
2
Key : c Value :
2
Key : d Value :
1
@RunWith(SpringRunner.class)
@SpringBootTest(classes = FXOAdapterApplication.class)
@Before
@Test
@After
@BeforeClass
@AfterClass
assertEquals(["message"],expected,acutal)
assertTrue([message],bolean condition expression)
assertNull([message],object)
assertNotNull()
assertFalse()
PowerMock
PowerMock is a framework that extends other mock
libraries giving them more powerful capabilities. PowerMock uses a custom
classloader and bytecode manipulation to enable mocking of static methods,
constructors, final classes and methods, private methods, removal of static
initializers and more.
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>1.6.5</version>
<scope>test</scope>
</dependency>
@RunWith(PowerMockRunner.class)
@PrepareForTest({Utils.class})
public class LocatorServiceTest {
private
LocatorServicelocatorServiceUnderTest;
@Before
public
void setUp() {
PowerMockito.mockStatic(Utils.class);
locatorServiceUnderTest = new LocatorService();
}
@Test
public
void testGeneratePointWithinDistance() {
int
distance = 111;
when(Utils.randomDistance(anyInt())).thenReturn(distance);
asserrTrue(expression)
==========
when(Utils.randomDistance(anyInt())).thenReturn(distance);
Mockito.when(mock.getGear()).thenReturn(TESTING_INITIAL_GEAR);
Assert.assertEquals(actualGear,
TESTING_INITIAL_GEAR + 2);
Mockito.verify(mock,
Mockito.times(2)).shiftGear(true);
===============
public class CalculateAreaTest {
@Mock
RectangleServicerectangleService;
@Mock
SquareServicesquareService;
@Mock
CircleServicecircleService;
@InjectMocks
CalculateAreacalculateArea;
@Before
public
void init()
{
MockitoAnnotations.initMocks(this);
}
@Test
public
void calculateRectangleAreaTest()
{
Mockito.when(rectangleService.area(5.0d,4.0d)).thenReturn(20d);
Double calculatedArea = this.calculateArea.calculateArea(Type.RECTANGLE,
5.0d, 4.0d);
Assert.assertEquals(new
Double(20d),calculatedArea);
}
}
//if excepectiong exception in junit testcase
@Test(expected
= NoSuchElementException.class)
public
void testRemoveException() {}
// test void method.
assertEquals
https://examples.javacodegeeks.com/core-java/junit/junit-test-void-method-example/
https://automationrhapsody.com/mock-static-methods-junit-powermock-example/
svn: centralized and only one repo
git: distributed and can create multiple
repositoreis.
https://www.journaldev.com/797/what-is-java-string-pool
Thereads:
RaceCondition:
is a situation, in which 2 or more threads are
accessing some shared resource and are tring to perform read/write operations
at the same time. symultaniously ,data get be redundent
resource can be any file or global variable
Critical block:
a code section that leads to race condition is
called Critical section.
Dead lock:
Deadlock referes to specific codition when 2 or
more threads are waiting for each other to release a resource.
Starvation.
live lock:
Mutex. Mutex is a mutual exclusion object that synchronizes
access to a resource. It is created with a unique name at the start of a
program. The Mutex is a locking mechanism that makes sure only one thread can
acquire the Mutex at a time and enter the critical section
Semaphore: wait():is called when a process wants
to accesss a resorce(when semaphore varibal is negative , the process wait is
bloked) signal(): is called when a process is done using a resource
This variable is used to solve critical section
problems and to achieve process synchronization in the multi processing
environment.
Monitor:
January 2014) In concurrent programming, a
monitor is a synchronization construct that allows threads to have both mutual
exclusion and the ability to wait (block) for a certain condition to become
false. Monitors also have a mechanism for signaling other threads that their
condition has been met.
https://www.youtube.com/watch?v=PQ5aK5wLCQE
Set<T> items = new HashSet<>();
return list.stream()
.filter(n -> !items.add(n)) // Set.add() returns false if the element was already in the set.
.collect(Collectors.toSet());
Map<Integer, String> map = new HashMap<>();
map.put(1, "linode.com");
map.put(2, "heroku.com");
//Map -> Stream -> Filter -> String
String result = map.entrySet().stream()
.filter(x -> "something".equals(x.getValue()))
.map(x->x.getValue())
.collect(Collectors.joining());
//Map -> Stream -> Filter -> MAP
Map<Integer, String> collect = map.entrySet().stream()
.filter(x -> x.getKey() == 2)
.collect(Collectors.toMap(x -> x.getKey(), x -> x.getValue()));
// or like this
Map<Integer, String> collect = map.entrySet().stream()
.filter(x -> x.getKey() == 3)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
Well explained . Great article on singleton pattern . There is also good singleton pattern example visit Singleton class example
ReplyDelete