Saturday, November 25, 2017

How to remove duplicate elements from an ArrayList in Java


How to remove duplicate elements from an ArrayList in Java.

Ø  ArrayList allows adding duplicate elements, sometime there may be a requirement to remove duplicates from a list.
Ø  In this post will talk about the way to do it.

1St  Approach:

Ø  First thing  that will come to mind is create a new list and loop through the created old list.

Ø  Use  contains() method to check if element is already existed to the new list.

Ø  If element is  not existed then add it to the new list otherwise discard it.

Program:

                  package com.coding.core;
                  import java.util.ArrayList;
                  import java.util.List;

              public class RemoveDuplicateElements {
              public static void main(String[] args) {
List<String> gameList = new ArrayList<String>();
gameList.add("Portal");
gameList.add("Chess");
gameList.add("Roulette");
gameList.add("poker");
gameList.add("poker");
gameList.add("poker");
gameList.add("Carrom");
// Create a new ArrayList

System.out.println("********************************************************");

List<String> newGameList = new ArrayList<String>();

for (String gameName : gameList) {
if (!newGameList.contains(gameName)) {
newGameList.add(gameName);

}
System.out.println("Duplicate gameList : " + gameName);
}
System.out.println("********************************************************");

for (String uniqueGameName : newGameList) {
System.out.println("Game Names : " + uniqueGameName);
}

System.out.println("********************************************************");
}

   OUTPUT :

  ********************************************************************************
                         Game Name : Portal
                         Game Name : Chess
                         Game Name : Roulette
                         Game Name : poker
                         Game Name : Carrom
    
  ********************************************************************************
  


2nd Approach :  

    But that much code is really not required.

    Collection framework itself provides several options to remove duplicates from an arraylist.

    We can simply use a HashSet to do the trick of removing the duplicate elements.

    HashSet only allows unique elements and we'll use that feature of HashSet to remove duplicates.

    Only problem is it won't retain the order of the list.

   Program:

    package com.coding.core;

    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;

    public class RemovingDuplicatesByUsingHashSet {
public static void main(String[] args) {
List<String> gameList = new ArrayList<String>();
gameList.add("Portal");
gameList.add("Chess");
gameList.add("Roulette");
gameList.add("poker");
gameList.add("poker");
gameList.add("poker");
gameList.add("Carrom");

// Create HashSet
Set<String> gameSet = new HashSet<String>(gameList);
// remove all the elements from the list
gameList.clear();
gameList.addAll(gameSet);

System.out.println("********************************************************");
for (String name : gameList) {
System.out.println("Game Name - " + name);
}
System.out.println("********************************************************");
}

     ========================================================================
    If  you want retain the order then you will go with LinkedHashSet:

    Please find below program:
    package com.coding.core;

    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.LinkedHashSet;
    import java.util.List;
    import java.util.Set;
    public class RemovingDuplicatesByUsingHashSet {

public static void main(String[] args) {
// TODO Auto-generated method stub

List<String> gameList = new ArrayList<String>();
gameList.add("Portal");
gameList.add("Chess");
gameList.add("Roulette");
gameList.add("poker");
gameList.add("poker");
gameList.add("poker");
gameList.add("Carrom");

// Create HashSet
//Set<String> gameSet = new HashSet<String>(gameList);
Set<String> gameSet = new LinkedHashSet<String>(gameList);
// remove all the elements from the list
gameList.clear();

gameList.addAll(gameSet);

System.out.println("********************************************************");
for (String name : gameList) {
System.out.println("Game Name - " + name);
}
System.out.println("********************************************************");
} }

    Out Put :
   ********************************************************
     Game Name - Portal
    Game Name - Chess
    Game Name - Roulette
    Game Name - poker
    Game Name - Carrom
  ********************************************************

Java 8 streams provide a very simple way to remove duplicate elements from a list. 
Using the distinct method.


package com.coding.core.sort;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Java8RemoveDuplicates {

public static void main(String[] args) {
// TODO Auto-generated method stub

List<String> gameList = new ArrayList<String>();
gameList.add("Portal");
gameList.add("Chess");
gameList.add("Roulette");
gameList.add("poker");
gameList.add("poker");
gameList.add("poker");
gameList.add("Carrom");

gameList = gameList.stream().distinct().collect(Collectors.toList());

System.out.println("*****************************************************");

for (String name : gameList) {
System.out.println("Game Name - " + name);
}
System.out.println("******************************************************");

}

}}
output:
     ******
   ********************************************************
        Game Name - Portal
        Game Name - Chess
        Game Name - Roulette
        Game Name - poker
        Game Name - Carrom
   ********************************************************

you can see that the duplicate element is removed and original order is retained too and all that is done in a single line.



Monday, November 20, 2017

How to rename JSON properties using Jackson annotations?

JsonIgnore Property Example :

  • In this example you will know how to ignore json property using @JsonIgnore jackson annotation.
  • If you annotate any property with @JsonIgnore annotation, it will be ignored at runtime.
=======================================================================
package com.coding.Json;

import java.io.File;
import java.io.IOException;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonIgnoreExample {

public static void main(String[] args) {
// TODO Auto-generated method stub
ObjectMapper mapper = new ObjectMapper();
        try {
            // reading json input from the file and mapping to object
            File jsonInputFile = new File("D:\\Employee.txt");
            Employee emp = mapper.readValue(jsonInputFile, Employee.class);
            System.out.println(emp);
            // converting object to string value
            String jsonStr 
                    = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
            System.out.println(jsonStr);
             
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}
=======================================================================

class Employee {

@JsonProperty("emp_id")
private int empId;

@JsonProperty("emp_name")
private String name;

@JsonProperty("emp_designation")
private String designation;

private String department;
@JsonIgnore
private int salary; // salary ignored

public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("************************************");
sb.append("\nempId: ").append(empId);
sb.append("\nname: ").append(name);
sb.append("\ndesignation: ").append(designation);
sb.append("\ndepartment: ").append(department);
sb.append("\nsalary: ").append(salary);
sb.append("\n************************************");
return sb.toString();
}

public int getEmpId() {
return empId;
}

public void setEmpId(int empId) {
this.empId = empId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDesignation() {
return designation;
}

public void setDesignation(String designation) {
this.designation = designation;
}

public String getDepartment() {
return department;
}

public void setDepartment(String department) {
this.department = department;
}

public int getSalary() {
return salary;
}

public void setSalary(int salary) {
this.salary = salary;
}
}
========================================================================
OUTPUT:

************************************
empId: 1017
name: Nagesh Y
designation: Manager
department: Java2Novice
salary: 0
************************************
{
  "department" : "Java2Novice",
  "emp_id" : 1017,
  "emp_name" : "Nagesh Y",
  "emp_designation" : "Manager"
}


JSONConvertStringToMap

program for convert JSON from String to Map:

Example:
package com.coding.Json;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONConvertStringToMap {

public static void main(String a[]) {

String jsonStr = "{\"name\":\"Ramesh\", \"job\":\"SoftWare Engineer\"}";
Map<String, String> resultMap = new HashMap<String, String>();
ObjectMapper mapperObj = new ObjectMapper();

System.out.println("Input Json: " + jsonStr);
try {
resultMap = mapperObj.readValue(jsonStr, new TypeReference<HashMap<String, String>>() {
});
System.out.println("Output Map: " + resultMap);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}





JSON TUTORIAL

Json Examples:

1) It is a simple and easy to read,write and data exchange format
2) It is popular and implement in many project in worldwide
3) We have main three third party libraries to process the JSON data.
JSON.simple , Jackson, Gson
Json is alternate  for XML.

This post explains Jackson data-binding, which is a common approach when dealing with JSON using Jackson API in your Java projects. 

ObjectMapper is the main class used for data-binding. It comes with several reader/writer methods to perform the conversion from/to Java and JSON.

// *********************************************************************//

Read the data from JSON file  and populate java objects
ObjectMapper mapper = new ObjectMapper();
Object jsonData = mapper.readValue(json filename, Java Object type)

//**********************************************************************//

//Write JSON from java objects
 ObjectMapper mapper = new ObjectMapper();
Object value = mapper.writeValue(json file Name,java Object Type);

//*********************************************************************//

Example write the java Object Data to json file:

package com.coding.core;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;

public class JSONWriteData {

public static void main(String[] args) {
// TODO Auto-generated method stub
       // API class which have may many useful methods
ObjectMapper mapper = new ObjectMapper();

Emp empObject = new Emp();
Emp empObject1 = new Emp();
Emp empObject2 = new Emp();

empObject.setEmpId(101);
empObject.setEmpName("Ritwik");
empObject.setEmpSal(39099.00);

empObject1.setEmpId(101);
empObject1.setEmpName("Ritwik");
empObject1.setEmpSal(39099.00);

empObject2.setEmpId(101);
empObject2.setEmpName("Ritwik");
empObject2.setEmpSal(39099.00);

List<Emp> empList = new ArrayList<Emp>();
empList.add(empObject);
empList.add(empObject1);
empList.add(empObject2);

try {
// mapper.writeValue(new File("d:/result.json"), empList);
mapper.writerWithDefaultPrettyPrinter().writeValue(new File("d:/result.json"), empList);
} catch (Exception e) {
// TODO: handle exception
}

}
}

//*****************************************************************//
// Employee class:

class Emp {
private int empId;
private String empName;
private double empSal;

public int getEmpId() {
return empId;
}

public void setEmpId(int empId) {
this.empId = empId;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public double getEmpSal() {
return empSal;
}

public void setEmpSal(double empSal) {
this.empSal = empSal;
}

}
//****************************************************************************//

OUT PUT:
[ {
  "empId" : 101,
  "empName" : "Ritwik",
  "empSal" : 39099.0
}, {
  "empId" : 101,
  "empName" : "Ritwik",
  "empSal" : 39099.0
}, {
  "empId" : 101,
  "empName" : "Ritwik",
  "empSal" : 39099.0
} ]




Sunday, November 19, 2017

Java 8 Comparator Example using Lambda Expressions


                             Lambda Expressions with  Comparator Example
  1. Main purpose of Comparator is to sort  a Collection of Objects which can be compared with each other.
  2. Comparison can be done using Comparable interface as well, but it restrict you compare these objects in a single particular way only.
  3. If you want sort this collection, based on multiple fields , then you  have to use Comparator only.
  4. I am sharing some knowledge about lambda expressions
    Demo with Employee with four attributes, will see various use cases:

    class Employee {
private Integer id;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

private String firstName;
private String lastName;
private Integer age;

public Employee(Integer id, String firstName, String lastName, Integer age)
 {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
 }

@Override
public String toString() 
{
return "\n[" + this.id + "," + this.firstName + "," + this.lastName + "," + this.age + "]";
}

@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Employee)) {
return false;
}
Employee empObj = (Employee) obj;
return this.age == empObj.age && this.firstName.equalsIgnoreCase(empObj.firstName)
&& this.lastName.equalsIgnoreCase(empObj.lastName);
}

@Override
public int hashCode() {
int hash = 1;
hash = hash * 17 + this.firstName.hashCode();
hash = hash * 17 + this.lastName.hashCode();
hash = hash * 31 + this.age;
return hash;
}
}

class Employee {
private Integer id;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

private String firstName;
private String lastName;
private Integer age;

public Employee(Integer id, String firstName, String lastName, Integer age) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}

@Override
public String toString() {
return "\n[" + this.id + "," + this.firstName + "," + this.lastName + "," + this.age + "]";
}

@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof Employee)) {
return false;
}
Employee empObj = (Employee) obj;
return this.age == empObj.age && this.firstName.equalsIgnoreCase(empObj.firstName)
&& this.lastName.equalsIgnoreCase(empObj.lastName);
}

@Override
public int hashCode() {
int hash = 1;
hash = hash * 17 + this.firstName.hashCode();
hash = hash * 17 + this.lastName.hashCode();
hash = hash * 31 + this.age;
return hash;
}
}
Main Class:


package com.coding.core.sort;

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

public class ComparatorWithLamda {

public static void main(String[] args) {
// TODO Auto-generated method stub

// 1) Sort all employees by first name
List<Employee> employees = getEmployees();

// Sort all employees by first name
employees.sort(Comparator.comparing(e -> e.getFirstName()));

// OR you can use below
employees.sort(Comparator.comparing(Employee::getFirstName));

System.out.println("*** sorted emps by First Name*********");
// Let's print the sorted list
System.out.println(employees);
System.out.println();

System.out.println("*******************************");
System.out.println("Sorted All emp's by Fname with reverse Order");
// Sort all employees by first name; And then reversed
Comparator<Employee> comparator = Comparator.comparing(e -> e.getFirstName());
employees.sort(comparator.reversed());

// Let's print the sorted list
System.out.println(employees);
System.out.println("*********************************");

}

private static List<Employee> getEmployees() {
List<Employee> employees = new ArrayList<>();
employees.add(new Employee(1, "Lokesh", "Gupta", 32));
employees.add(new Employee(2, "Rajesh", "Guru", 28));
employees.add(new Employee(3, "Avinash", "Rijesh", 52));
employees.add(new Employee(4, "Nirlam", "Tracy", 72));
employees.add(new Employee(5, "David", "Kameron", 19));
employees.add(new Employee(6, "Yashod", "kumar", 25));
employees.add(new Employee(7, "Karan", "Johar", 59));

return employees;
}
//Case3 :

/*4) Sort By first name and then by last name (sort on multiple fields)

Here we are sorting list of employees first by their first name, and then sort again the list of last name. Just as we apply sorting on SQL statements. It’s actually a very good feature.


Now you don’t need to always use sorting on multiple fields in SQL select statements, you can sort them in java as well.*/

// Sorting on multiple fields; Group by.
Comparator<Employee> groupByComparator = Comparator.comparing(Employee::getFirstName)
.thenComparing(Employee::getLastName);
employees.sort(groupByComparator);

System.out.println(employees);


}
Output:
***********Sorted All Employees by First Name*********
[
[3,Avinash,Rijesh,52], 
[5,David,Kameron,19], 
[7,Karan,Johar,59], 
[1,Lokesh,Gupta,32], 
[4,Nirlam,Tracy,72], 
[2,Rajesh,Guru,28], 
[6,Yashod,kumar,25]]

****************************************************
Sorted All Employees by First Name with reverse Order
[
[6,Yashod,kumar,25], 
[2,Rajesh,Guru,28], 
[4,Nirlam,Tracy,72], 
[1,Lokesh,Gupta,32], 
[7,Karan,Johar,59], 
[5,David,Kameron,19], 
[3,Avinash,Rijesh,52]]

*****************************************************




Find the Duplicate words in File

package com.coding.core;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
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;
import java.util.StringTokenizer;

public class FindDuplicateWordFromFile {

public Map<String, Integer> getWordCount(String fileName) {

FileInputStream fis = null;
DataInputStream dis = null;
BufferedReader br = null;
Map<String, Integer> wordMap = new HashMap<String, Integer>();
try {
fis = new FileInputStream(fileName);
dis = new DataInputStream(fis);
br = new BufferedReader(new InputStreamReader(dis));
String line = null;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, " ");
while (st.hasMoreTokens()) {
String tmp = st.nextToken().toLowerCase();
if (wordMap.containsKey(tmp)) {
wordMap.put(tmp, wordMap.get(tmp) + 1);
} else {
wordMap.put(tmp, 1);
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (Exception ex) {
}
}
return wordMap;
}

public List<Entry<String, Integer>> sortByValue(Map<String, Integer> wordMap) {

Set<Entry<String, Integer>> set = wordMap.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return (o2.getValue()).compareTo(o1.getValue());
}
});
return list;
}

public static void main(String a[]) {
FindDuplicateWordFromFile word = new FindDuplicateWordFromFile();
Map<String, Integer> wordMap = word
.getWordCount("C:/Users/Remash/workspace/Coding_Project/src/com/coding/core/Data.txt");
List<Entry<String, Integer>> list = word.sortByValue(wordMap);
for (Map.Entry<String, Integer> entry : list) {
System.out.println(entry.getKey() + " ==== " + entry.getValue());
}
}
}

How to Read a file

Read a File:

1) Java has a concept of working with streams of data.
2) You can say that a Java program reads sequences of bytes from an input stream (or writes into an output stream):
byte after byte,character after character,primitive after primitive.
3) Accordingly, Java defines various types of classes supporting streams,
for example, InputStream or OutputStream.
There are classes specifically meant for reading character streams such as Reader and Writer.


A Java application opens a file by creating an object and associating a stream of bytes with that object.
Similarly, when you finished using a file, the program should close the file—that is, make it no longer available to your application.



Class
Description
InputStream
Abstract class containing methods for performing input
OutputStream
Abstract class containing methods for performing output
FileInputStream
Child of InputStream that provides the capability to read from disk files
FileOutputStream
Child of OutputStream that provides the capability to write to disk files
PrintStream
Child of FilterOutputStream, which is a child of OutputStream; PrintStream handles output to a system’s standard (or default) output device, usually the monitor
BufferedInputStream
Child of FilterInputStream, which is a child of InputStream; BufferedInputStream handles input from a system’s standard (or default) input device, usually the keyboard

READING FROM A FILE
We will write a java program to read from file and print file data on the user screen. 
Let’s understand way to associate a File object with the input stream:
You can pass the filename to the constructor of the FileInputStream class.
You can create a File object by passing the filename to the File constructor.
 Then, you can pass the File object to the constructor of the FileInputStream class.
The second method has some benefits:
If you create a File object, you can use the File class methods, such as exists()and lastModified(), to retrieve file information. (Refer File Input Output Tutorial).

While working with stream classes we have to take care of checked exceptions, In our program, we are doing it using a try-catch block.

package com.coding.core;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class ReadDataFromFile {

public static void main(String[] args) {
// TODO Auto-generated method stub

File file = new File("C:/Users/Remash/workspace/Coding_Project/src/com/coding/core/Data.txt");
try (FileInputStream fis = new FileInputStream(file))
{
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}

}

}



How to remove duplicate elements from an ArrayList in Java

How to remove duplicate elements from an ArrayList in Java. Ø   ArrayList allows adding duplicate elements, sometime there may be...