Basic Java Knowledge
Core Java: Basics of Java Interview Questions
1) What is Java?
Java is the high-level, object-oriented, robust, secure programming language, platform-independent, high performance, Multithreaded, and portable programming language. It was developed by James Gosling in June 1991. It can also be known as the platform as it provides its own JRE and API.
2) List the features of Java Programming language.
There are the following features in Java Programming Language.
Simple: Java is easy to learn. The syntax of Java is based on C++ which makes easier to write the program in it.
Object-Oriented: Java follows the object-oriented paradigm which allows us to maintain our code as the combination of different type of objects that incorporates both data and behavior.
Portable: Java supports read-once-write-anywhere approach. We can execute the Java program on every machine. Java program (.java) is converted to bytecode (.class) which can be easily run on every machine.
Platform Independent: Java is a platform independent programming language. It is different from other programming languages like C and C++ which needs a platform to be executed. Java comes with its platform on which its code is executed. Java doesn't depend upon the operating system to be executed.
Secured: Java is secured because it doesn't use explicit pointers. Java also provides the concept of ByteCode and Exception handling which makes it more secured.
Robust: Java is a strong programming language as it uses strong memory management. The concepts like Automatic garbage collection, Exception handling, etc. make it more robust.
Architecture Neutral: Java is architectural neutral as it is not dependent on the architecture. In C, the size of data types may vary according to the architecture (32 bit or 64 bit) which doesn't exist in Java.
Interpreted: Java uses the Just-in-time (JIT) interpreter along with the compiler for the program execution.
High Performance: Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++).
Multithreaded: We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area. Threads are important for multi-media, Web applications, etc.
Distributed: Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand. It also supports functions from its native languages, i.e., C and C++.
4) What do you understand by Java virtual machine?
Java Virtual Machine is a virtual machine that enables the computer to run the Java program. JVM acts like a run-time engine which calls the main method present in the Java code. JVM is the specification which must be implemented in the computer system. The Java code is compiled by JVM to be a Bytecode which is machine independent and close to the native code.
5) What is the difference between JDK, JRE, and JVM?
JVM
JVM is an acronym for Java Virtual Machine; it is an abstract machine which provides the runtime environment in which Java bytecode can be executed. It is a specification which specifies the working of Java Virtual Machine. Its implementation has been provided by Oracle and other companies. Its implementation is known as JRE.
JVMs are available for many hardware and software platforms (so JVM is platform dependent). It is a runtime instance which is created when we run the Java class. There are three notions of the JVM: specification, implementation, and instance.
JRE
JRE stands for Java Runtime Environment. It is the implementation of JVM. The Java Runtime Environment is a set of software tools which are used for developing Java applications. It is used to provide the runtime environment. It is the implementation of JVM. It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
JDK
JDK is an acronym for Java Development Kit. It is a software development environment which is used to develop Java applications and applets. It physically exists. It contains JRE + development tools. JDK is an implementation of any one of the below given Java Platforms released by Oracle Corporation:
Standard Edition Java Platform
Enterprise Edition Java Platform
Micro Edition Java Platform
6) How many types of memory areas are allocated by JVM?
Many types:
Class(Method) Area: Class Area stores per-class structures such as the runtime constant pool, field, method data, and the code for methods.
Heap: It is the runtime data area in which the memory is allocated to the objects
Stack: Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and return. Each thread has a private JVM stack, created at the same time as the thread. A new frame is created each time a method is invoked. A frame is destroyed when its method invocation completes.
Program Counter Register: PC (program counter) register contains the address of the Java virtual machine instruction currently being executed.
Native Method Stack: It contains all the native methods used in the application.
7) What is JIT compiler?
Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the bytecode that have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here the term “compiler” refers to a translator from the instruction set of a Java virtual machine (JVM) to the instruction set of a specific CPU.
8) What is the platform?
A platform is the hardware or software environment in which a piece of software is executed. There are two types of platforms, software-based and hardware-based. Java provides the software-based platform.
9) What are the main differences between the Java platform and other platforms?
There are the following differences between the Java platform and other platforms.
Java is the software-based platform whereas other platforms may be the hardware platforms or software-based platforms.
Java is executed on the top of other hardware platforms whereas other platforms can only have the hardware components.
10) What gives Java its 'write once and run anywhere' nature?
The bytecode. Java compiler converts the Java programs into the class file (Byte Code) which is the intermediate language between source code and machine code. This bytecode is not platform specific and can be executed on any computer.
11)Explain public static void main(String args[]).
Public: Public is an access modifier. Public means that this Method will be accessible by any Class.
static : It is a keyword in java which identifies it is class based i.e it can be accessed without creating the instance of a Class. Since we want main method to be executed without any instance also, we use static.
Void: It is the return type of the method. Void defines the method which will not return any value.
main: This is the first method executed by JVM. The signature of method must be same.
[12] Why Java is platform independent?
Platform independent practically means “write once run anywhere”. Java is called so because of its byte codes which can run on any system irrespective of its underlying operating system.
[13] Why is Java not pure Object-oriented?
Java is not considered pure Object-oriented because it supports primitive data-types such as boolean, byte, char, int, float, double, long, short.
[14] Define class and object. Explain them with an example using java.
Class: A class is a user defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:
Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
Interfaces: A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
Object: It is a basic unit of Object Oriented Programming and represents the real life entities. A typical Java program creates many objects, which as you know, interact by invoking methods. An object consist of :
State : It is represented by attributes of an object. It also reflect the properties of an object.
Behavior : It is represented by methods of an object. It also reflects the response of an object with other objects.
Identity : It gives a unique name to an object and enables one object to interact with other objects.
For Example: Employee is an example of a class
A specific employee with unique identification is an example of an object.
class Employee
{
// instance variables declaration
// Methods definition
}
An object of employee is a specific employee
Employee empObj = new Employee();
One of the objects of Employee is referred by ‘empObj’
[15] What are constructors in Java?
In Java, constructor refers to a block of code which is used to initialize an object. It must have the same name as that of the class. Also, it has no return type and it is automatically called when an object is created.
If a class does not explicitly declare any, the Java compiler automatically provides a no-argument constructor, also called the default constructor.
This default constructor calls the class parent’s no-argument constructor (as it contain only one statement i.e. super();), or the Object class constructor if the class has no other parent (as Object class is parent of all classes either directly or indirectly).
There are two types of constructors:
Default constructor
Parameterized constructor
[16] What are the different ways to create objects in Java?
There are many different ways to create objects in Java.
[17] What’s the purpose of Static methods and static variables?
When there is a requirement to share a method or a variable between multiple objects of a class instead of creating separate copies for each object, we use static keyword to make a method or variable shared for all objects.
Static variable: Static variables are also known as Class variables.
These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
Static variables are created at start of program execution and destroyed automatically when execution ends.
To access static variables, we need not to create any object of that class.
Static methods: A static method can be accessed without creating the objects. Just by using the Class name the method can be accessed. Static method can only access static variables and not local or global non-static variables.
For Example:
public class StaticMethod {
public static void printMe()
{
System.out.println("Static Method access directly by class name!");
}
}
public class MainClass {
public static void main(String args[])
{
StaticMethod.printMe();
}
}
[18] Why static methods cannot access non static variables or methods?
Ans) A static method cannot access non static variables or methods because static methods can be accessed without instantiating the class, so if the class is not instantiated the variables are not initialized and thus cannot be accessed from a static method.
[19] What is a static class?
A class can be said to be static class if all the variables and methods of the class are static and the constructor is private. Making the constructor private will prevent the class to be instantiated. So the only possibility to access is using Class name only.
[20] How many types of Variable? Explain.
There are three types of variables in Java:
Local Variables
Instance Variables
Static Variables
Local Variables: A variable defined within a block or method or constructor is called local variable.
These variable are created when the block in entered or the function is called and destroyed after exiting from the block or when the call returns from the function.
The scope of these variables exists only within the block in which the variable is declared. i.e. we can access these variable only within that block.
// Java program to demonstrate local variables
public class LocalVariable
{
public void getLocalVarValue()
{
// local variable age
int localVar = 0;
localVar = localVar + 11;
System.out.println("value of local variable" +
" is: " + localVar);
}
public static void main(String args[])
{
LocalVariable obj = new LocalVariable();
obj.getLocalVarValue();
}
}
Output:
value of local variable is: 11
In the above program the variable localVar is local variable to the function getLocalVarValue(). If we use the variable localVar outside getLocalVarValue() function, the compiler will produce an error as
“Cannot find the symbol localVar”.
Instance Variables: Instance variables are non-static variables and are declared in a class outside any method, constructor or block.
As instance variables are declared in a class, these variables are created when an object of the class is created and destroyed when the object is destroyed.
Unlike local variables, we may use access specifiers for instance variables. If we do not specify any access specifier then the default access specifier will be used.
/ Java program to demonstrate instance variables
public class InstanceVariable {
int instanceVarId;
String instanceVarName;
public static void main(String args[])
{
InstanceVariable obj = new InstanceVariable();
obj.instanceVarId = 0001;
obj.instanceVarName = "InstanceVariable1";
System.out.println("Displaying first Object:");
System.out.println("instanceVarId==" + obj.instanceVarId);
System.out.println("instanceVarName==" + obj.instanceVarName);
InstanceVariable obj1 = new InstanceVariable();
obj1.instanceVarId = 0002;
obj1.instanceVarName = "InstanceVariable2";
System.out.println("Displaying Second Object:");
System.out.println("instanceVarId==" + obj.instanceVarId);
System.out.println("instanceVarName==" + obj.instanceVarName);
}
}
Output:
Displaying first Object:
instanceVarId==1
instanceVarName==InstanceVariable1
Displaying Second Object:
instanceVarId==1
instanceVarName==InstanceVariable1
In the above program the variables i.e. instanceVarId, instanceVarName are instance variables. In case we have multiple objects as in the above program, each object will have its own copies of instance variables. It is clear from the above output that each object will have its own copy of instance variable.
Static variable: Static variables are also known as Class variables.
These variables are declared similarly as instance variables, the difference is that static variables are declared using the static keyword within a class outside any method constructor or block.
Unlike instance variables, we can only have one copy of a static variable per class irrespective of how many objects we create.
Static variables are created at start of program execution and destroyed automatically when execution ends.
To access static variables, we need not to create any object of that class, we can simply access the variable as:
/ Java program to demonstrate static variables
public class StaticVar {
private static int count = 0;
private int nonStaticCount = 0;
public void incrementCounter()
{
count++;
nonStaticCount++;
}
public static int getStaticCount()
{
return count;
}
public int getNonStaticCount()
{
return nonStaticCount;
}
public static void main(String args[])
{
StaticVar stVarObj1 = new StaticVar();
StaticVar stVarObj2 = new StaticVar();
stVarObj1.incrementCounter();
stVarObj2.incrementCounter();
System.out.println("Static count for stVarObj1: " +
stVarObj1.getStaticCount());
System.out.println("NonStatic count for stVarObj1: " +
stVarObj1.getNonStaticCount());
System.out.println("Static count for stVarObj2: " +
stVarObj2.getStaticCount());
System.out.println("NonStatic count for stVarObj2: " +
stVarObj2.getNonStaticCount());
}
}
Output:
Static count for stVarObj1: 2
NonStatic count for stVarObj1: 1
Static count for stVarObj2: 2
NonStatic count for stVarObj2: 1
In the above program stVarObj1 and stVarObj2 share the same instance of static variable count hence if the value is incremented by one object, the incremented value will be reflected for stVarObj1 and stVarObj2.
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is loaded first by the classloader. There are three built-in classloaders in Java.
Bootstrap ClassLoader: This is the first classloader which is the superclass of Extension classloader. It loads the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net package classes, java.util package classes, java.io package classes, java.sql package classes, etc.
Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader. It loads the jar files located inside $JAVA_HOME/jre/lib/ext directory.
System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the class files from the classpath. By default, the classpath is set to the current directory. You can change the classpath using "-cp" or "-classpath" switch. It is also known as Application classloader.
12) Is Empty .java file name a valid source file name?
Yes, Java allows to save our java file by .java only, we need to compile it by javac .java and run by java classname Let's take a simple example:
//save by .java only
class A{
public static void main(String args[]){
System.out.println("Hello java");
}
}
//compile by javac .java
//run by java A
compile it by javac .java
run it by java A
[21] Is delete, next, main, exit or null keyword in java?
No.
[22] If I don't provide any arguments on the command line, then what will the value stored in the String array passed into the main() method, empty or NULL?
It is empty, but not null.
[23] What if I write static public void instead of public static void?
The program compiles and runs correctly because the order of specifiers doesn't matter in Java.
[24] What is the default value of the local variables?
The local variables are not initialized to any default value, neither primitives nor object references.
[25] What are the various access specifiers in Java?
In Java, access specifiers are the keywords which are used to define the access scope of the method, class, or a variable. In Java, there are four access specifiers given below.
Public The classes, methods, or variables which are defined as public, can be accessed by any class or method.
Protected Protected can be accessed by the class of the same package, or by the sub-class of this class, or within the same class.
Default Default are accessible within the package only. By default, all the classes, methods, and variables are of default scope.
Private The private class, methods, or variables defined as private can be accessed within the class only.
[26] What is the purpose of static methods and variables?
The methods or variables defined as static are shared among all the objects of the class. The static is the part of the class and not of the object. The static variables are stored in the class area, and we do not need to create the object to access such variables. Therefore, static is used in the case, where we need to define variables or methods which are common to all the objects of the class.
For example, In the class simulating the collection of the students in a college, the name of the college is the common attribute to all the students. Therefore, the college name will be defined as static.
[27] What are the advantages of Packages in Java?
There are various advantages of defining packages in Java.
- Packages avoid the name clashes.
- The Package provides easier access control.
- We can also have the hidden classes that are not visible outside and used by the package.
- It is easier to locate the related classes.
[28] What is the output of the following Java program?
class Test
{
public static void main (String args[])
{
System.out.println(10 + 20 + "Javatpoint");
System.out.println("Javatpoint" + 10 + 20);
}
}
The output of the above code will be
30Javatpoint
Javatpoint1020
Explanation
In the first case, 10 and 20 are treated as numbers and added to be 30. Now, their sum 30 is treated as the string and concatenated with the string Javatpoint. Therefore, the output will be 30Javatpoint.
In the second case, the string Javatpoint is concatenated with 10 to be the string Javatpoint10 which will then be concatenated with 20 to be Javatpoint1020.
[29] What is the output of the following Java program?
class Test
{
public static void main (String args[])
{
System.out.println(10 * 20 + "Javatpoint");
System.out.println("Javatpoint" + 10 * 20);
}
}
The output of the above code will be
200Javatpoint
Javatpoint200
Explanation
In the first case, The numbers 10 and 20 will be multiplied first and then the result 200 is treated as the string and concatenated with the string Javatpoint to produce the output 200Javatpoint.
In the second case, The numbers 10 and 20 will be multiplied first to be 200 because the precedence of the multiplication is higher than addition. The result 200 will be treated as the string and concatenated with the string Javatpointto produce the output as Javatpoint200.
[30] What is the output of the following Java program?
class Test
{
public static void main (String args[])
{
for(int i=0; 0; i++)
{
System.out.println("Hello Javatpoint");
}
}
}
The above code will give the compile-time error because the for loop demands a boolean value in the second part and we are providing an integer value, i.e., 0.
[31] // Java program to demonstrate static variables
public class StaticVar {
private static int count = 0;
private int nonStaticCount = 0;
public void incrementCounter()
{
count++;
nonStaticCount++;
}
public static int getStaticCount()
{
return count;
}
public int getNonStaticCount()
{
return nonStaticCount;
}
public static void main(String args[])
{
StaticVar stVarObj1 = new StaticVar();
StaticVar stVarObj2 = new StaticVar();
stVarObj1.incrementCounter();
stVarObj2.incrementCounter();
System.out.println("Static count for stVarObj1: " +
stVarObj1.getStaticCount());
System.out.println("NonStatic count for stVarObj1: " +
stVarObj1.getNonStaticCount());
System.out.println("Static count for stVarObj2: " +
stVarObj2.getStaticCount());
System.out.println("NonStatic count for stVarObj2: " +
stVarObj2.getNonStaticCount());
}
}
Output:
Static count for stVarObj1: 2
NonStatic count for stVarObj1: 1
Static count for stVarObj2: 2
NonStatic count for stVarObj2: 1
In the above program stVarObj1 and stVarObj2 share the same instance of static variable count hence if the value is incremented by one object, the incremented value will be reflected for stVarObj1 and stVarObj2.
[32] Blank Final in Java
A final variable in Java can be assigned a value only once, we can assign a value either in declaration or later.
final int i = 10;
i = 30; // Error because i is final.
A blank final variable in Java is a final variable that is not initialized during declaration. Below is a simple example of blank final.
// A simple blank final example
final int i;
i = 30;
How are values assigned to blank final members of objects?
Values must be assigned in constructor.
// A sample Java program to demonstrate use and
// working of blank final
class Test
{
// We can initialize here, but if we
// initialize here, then all objects get
// the same value. So we use blank final
final int i;
Test(int x)
{
// Since we have initialized above, we
// must initialize i in constructor.
// If we remove this line, we get compiler
// error.
i = x;
}
}
// Driver Code
class Main
{
public static void main(String args[])
{
Test t1 = new Test(10);
System.out.println(t1.i);
Test t2 = new Test(20);
System.out.println(t2.i);
}
}
Output:
10
20
If we have more than one constructors or overloaded constructor in class, then blank final variable must be initialized in all of them. However constructor chaining can be used to initialize the blank final variable.
// A Java program to demonstrate that we can
// use constructor chaining to initialize
// final members
class Test
{
final public int i;
Test(int val) { this.i = val; }
Test()
{
// Calling Test(int val)
this(10);
}
public static void main(String[] args)
{
Test t1 = new Test();
System.out.println(t1.i);
Test t2 = new Test(20);
System.out.println(t2.i);
}
}
Output:
10
20
Blank final variables are used to create immutable objects (objects whose members can’t be changed once initialized).
[32]final variables in Java
In Java, when final keyword is used with a variable of primitive data types (int, float, .. etc), value of the variable cannot be changed.
For example following program gives error because i is final.
public class Test {
public static void main(String args[]) {
final int i = 10;
i = 30; // Error because i is final.
}
}
When final is used with non-primitive variables (Note that non-primitive variables are always references to objects in Java), the members of the referred object can be changed. final for non-primitive variables just mean that they cannot be changed to refer to any other object
class Test1 {
int i = 10;
}
public class Test2 {
public static void main(String args[]) {
final Test1 t1 = new Test1();
t1.i = 30; // Works
}
}
HashSet vs TreeSet in Java
Speed and internal implementation
HashSet : For operations like search, insert and delete. It takes constant time for these operations on average. HashSet is faster than TreeSet. HashSet is Implemented using a hash table.
TreeSet : TreeSet takes O(Log n) for search, insert and delete which is higher than HashSet. But TreeSet keeps sorted data. Also, it supports operations like higher() (Returns least higher element), floor(), ceiling(), etc. These operations are also O(Log n) in TreeSet and not supported in HashSet. TreeSet is implemented using a Self Balancing Binary Search Tree (Red-Black Tree). TreeSet is backed by TreeMap in Java.
Ordering
Elements in HashSet are not ordered. TreeSet maintains objects in Sorted order defined by either Comparable or Comparator method in Java. TreeSet elements are sorted in ascending order by default. It offers several methods to deal with the ordered set like first(), last(), headSet(), tailSet(), etc.
Null Object
HashSet allows null object. TreeSet doesn’t allow null Object and throw NullPointerException, Why, because TreeSet uses compareTo() method to compare keys and compareTo() will throw java.lang.NullPointerException.
Comparison
HashSet uses equals() method to compare two object in Set and for detecting duplicates. TreeSet uses compareTo() method for same purpose.
If equals() and compareTo() are not consistent, i.e. for two equal object equals should return true while compareTo() should return zero, than it will break contract of Set interface and will allow duplicates in Set implementations like TreeSet
If you want a sorted Set then it is better to add elements to HashSet and then convert it into TreeSet rather than creating a TreeSet and adding elements to it.
HashSet example
// Java program to demonstrate working of
// HashSet
import java.util.HashSet;
class HashSetDemo {
public static void main(String[] args)
{
// Create a HashSet
HashSet<String> hset = new HashSet<String>();
// add elements to HashSet
hset.add("geeks");
hset.add("for");
hset.add("practice");
hset.add("contribute");
// Duplicate removed
hset.add("geeks");
// Displaying HashSet elements
System.out.println("HashSet contains: ");
for (String temp : hset) {
System.out.println(temp);
}
}
}
Output:
HashSet contains:
practice
geeks
for
contribute
TreeSet example
// Java program to demonstrate working of
// TreeSet.
import java.util.TreeSet;
class TreeSetDemo {
public static void main(String[] args)
{
// Create a TreeSet
TreeSet<String> tset = new TreeSet<String>();
// add elements to HashSet
tset.add("geeks");
tset.add("for");
tset.add("practice");
tset.add("contribute");
// Duplicate removed
tset.add("geeks");
// Displaying TreeSet elements
System.out.println("TreeSet contains: ");
for (String temp : tset) {
System.out.println(temp);
}
}
}
Output:
TreeSet contains:
contribute
for
geeks
practice
[33] When to prefer TreeSet over HashSet
1. Sorted unique elements are required instead of unique elements. The sorted list given by TreeSet is always in ascending order.
2. TreeSet has greater locality than HashSet.If two entries are near by in the order, then TreeSet places them near each other in data structure and hence in memory, while HashSet spreads the entries all over memory regardless of the keys they are associated to.
3. TreeSet uses Red- Black tree algorithm underneath to sort out the elements. When one need to perform read/write operations frequently, then TreeSet is a good choice.
4. LinkedHashSet is another data structure that is between these two. It provides time complexities like HashSet and maintains order of insertion (Note that this is not sorted order, but the order in which elements are inserted).
[34]Sort elements by frequency | Set 5 (using Java Map)
Given an integer array, sort the array according to the frequency of elements in decreasing order, if frequency of two elements are same then sort in increasing order
Examples:
Input: arr[] = {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12}
Output: 3 3 3 3 2 2 2 12 12 4 5
Explanation :
No. Freq
2 : 3
3 : 4
4 : 1
5 : 1
12 : 2
Input: arr[] = {4, 4, 2, 2, 2, 2, 3, 3, 1, 1, 6, 7, 5}
Output: 2 2 2 2 1 1 3 3 4 4 5 6 7
Approach:
Java Map has been used in this set to solve the problem. The java.util.Map interface represents a mapping between a key and a value. The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types.
In the below program:
Get the element with its count in a Map
By using the Comparator Interface, compare the frequency of an elements in a given list.
Use this comparator to sort the list by implementing Collections.sort() method.
Print the sorted list.
Program:
import java.util.*;
public class GFG {
// Driver Code
public static void main(String[] args)
{
// Declare and Initialize an array
int[] array = { 4, 4, 2, 2, 2, 2, 3, 3, 1, 1, 6, 7, 5 };
Map<Integer, Integer> map = new HashMap<>();
List<Integer> outputArray = new ArrayList<>();
// Assign elements and their count in the list and map
for (int current : array) {
int count = map.getOrDefault(current, 0);
map.put(current, count + 1);
outputArray.add(current);
}
// Compare the map by value
SortComparator comp = new SortComparator(map);
// Sort the map using Collections CLass
Collections.sort(outputArray, comp);
// Final Output
for (Integer i : outputArray) {
System.out.print(i + " ");
}
}
}
// Implement Comparator Interface to sort the values
class SortComparator implements Comparator<Integer> {
private final Map<Integer, Integer> freqMap;
// Assign the specified map
SortComparator(Map<Integer, Integer> tFreqMap)
{
this.freqMap = tFreqMap;
}
// Compare the values
@Override
public int compare(Integer k1, Integer k2)
{
// Compare value by frequency
int freqCompare = freqMap.get(k2).compareTo(freqMap.get(k1));
// Compare value if frequency is equal
int valueCompare = k1.compareTo(k2);
// If frequency is equal, then just compare by value, otherwise -
// compare by the frequency.
if (freqCompare == 0)
return valueCompare;
else
return freqCompare;
}
}
Output:
2 2 2 2 1 1 3 3 4 4 5 6 7
Time Complexity : O(n Log n)
I like this post very much
ReplyDelete