How to read/write CSV file to Map in java

Posted on Updated on

As you see in last article, how to read a CSV file into Java object with the help of Jackson API. In this article, we will see how to write a list of Map ( List<Map<String,String>> ) into a CSV file in your machine and again read it through with Jackson API.

Add this dependency in your pom.xml file to used Jackson API in your application.

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-csv</artifactId>
  <version>2.7.0</version>
</dependency>

 

Below are a sample example of reading or writing a CSV file with the help of Jackson API, which makes it very easy to write or read the CSV file into Java Object.

 


package com.example;

import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.*;
import java.util.*;

/**
 * Created by MYPC on 8/1/2016.
 */
public class ConvertMapToCSVTest {
    public static void main(String[] args) throws IOException {

        List<HashMap<String, String>> myArrList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> map;

        /*** Rows 1 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C001");
        map.put("Name", "Ajay Kumar");
        map.put("Email", "ajay@gmail.com");
        map.put("CountryCode", "TH");
        map.put("Budget", "1000000");
        map.put("Used", "600000");
        myArrList.add(map);

        /*** Rows 2 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C002");
        map.put("Name", "Rahul Kumar");
        map.put("Email", "Rahul.kumar@gmail.com");
        map.put("CountryCode", "UK");
        map.put("Budget", "2000000");
        map.put("Used", "800000");
        myArrList.add(map);

        /*** Rows 3 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C003");
        map.put("Name", "Wasim Akram");
        map.put("Email", "waism.atnet@rediff.com");
        map.put("CountryCode", "US");
        map.put("Budget", "3000000");
        map.put("Used", "600000");
        myArrList.add(map);

        /*** Rows 4 ***/
        map = new HashMap<String, String>();
        map.put("CustomerID", "C004");
        map.put("Name", "Santosh Kumar");
        map.put("Email", "santosh.ku@yahoo.com");
        map.put("CountryCode", "US");
        map.put("Budget", "4000000");
        map.put("Used", "100000");
        myArrList.add(map);

        File file = new File("d:\\sample.csv");
        // Create a File and append if it already exists.
        Writer writer = new FileWriter(file, true);
        Reader reader = new FileReader(file);
        //Copy List of Map Object into CSV format at specified File location.
        csvWriter(myArrList, writer);
        //Read CSV format from specified File location and print on console..
        csvReader(reader);
    }

    /**
     * @param listOfMap
     * @param writer
     * @throws IOException
     */
    public static void csvWriter(List<HashMap<String, String>> listOfMap, Writer writer) throws IOException {
        CsvSchema schema = null;
        CsvSchema.Builder schemaBuilder = CsvSchema.builder();
        if (listOfMap != null && !listOfMap.isEmpty()) {
            for (String col : listOfMap.get(0).keySet()) {
                schemaBuilder.addColumn(col);
            }
            schema = schemaBuilder.build().withLineSeparator("\r").withHeader();
        }
        CsvMapper mapper = new CsvMapper();
        mapper.writer(schema).writeValues(writer).writeAll(listOfMap);
        writer.flush();
    }

    /**
     * 
     * @param collection
     * @param writer
     * @param 
     * @throws IOException
     */
    public static  void csvWriter(Collection collection, Writer writer) throws IOException {
        if (collection != null && collection.size() > 0) {
            CsvMapper mapper = new CsvMapper();
            Object[] objects = collection.toArray();
            Class type = objects[0].getClass();
            CsvSchema schema = mapper.schemaFor(type).withHeader();
            mapper.writer(schema).writeValues(writer).write(objects);
        } else {
            writer.write("No Data");
        }
        writer.flush();
    }


    /**
     * @param reader
     * @throws IOException
     */

    public static void csvReader(Reader reader) throws IOException {
        Iterator<Map<String, String>> iterator = new CsvMapper()
                .readerFor(Map.class)
                .with(CsvSchema.emptySchema().withHeader())
                .readValues(reader);
        while (iterator.hasNext()) {
            Map<String, String> keyVals = iterator.next();
            System.out.println(keyVals);
        }
    }
}


A CSV file is created at specified location i.e d:\\sample.csv in file system.

Email,Used,Budget,CustomerID,CountryCode,Name
ajay@gmail.com,600000,1000000,C001,TH,"Ajay Kumar"
Rahul.kumar@gmail.com,800000,2000000,C002,UK,"Rahul Kumar"
waism.atnet@rediff.com,600000,3000000,C003,US,"Wasim Akram"
santosh.ku@yahoo.com,100000,4000000,C004,US,"Santosh Kumar"

Reading sample.csv file from file system.

{Email=ajay@gmail.com, Used=600000, Budget=1000000, CustomerID=C001, CountryCode=TH, Name=Ajay Kumar}
{Email=Rahul.kumar@gmail.com, Used=800000, Budget=2000000, CustomerID=C002, CountryCode=UK, Name=Rahul Kumar}
{Email=waism.atnet@rediff.com, Used=600000, Budget=3000000, CustomerID=C003, CountryCode=US, Name=Wasim Akram}
{Email=santosh.ku@yahoo.com, Used=100000, Budget=4000000, CustomerID=C004, CountryCode=US, Name=Santosh Kumar}

Hoping, It would be helpful !! Thanks

JSON Schema Validation example in java

Posted on

Validating input is a good programming practice than spending times to trying to guard each line of codes against all the way the input goes wrong.

This is especially true when we are writing a web service that deal with input data of a PUT,POST,DELETE and GET method with MIME type JavaScript Object Notation (JSON) .  JSON data is formatted as a key & value pair and each key & value represent a properties name and value separated by the colon (:).

In last post, we have seen the Jackson framework that is used to marshaling and unmarshalling the JSON data to Java object and vice-versa, But validating JSON data is another task, unfortunately Jackson framework does not  provide to do validate JSON data.

json-schema-validator available at https://github.com is quite popular with Java developer to validate JSON data against Schema file.

JSON schema is:

  • A way of describing your existing data format
  • Written in clear, human and machine readable, documentation
  • Complete structural validation useful for
    • Automated testing
    • Validating client submitted data

Look at the below Schema file. This schema file exactly tells, in Input JSON data , “id” must be String type, “amount” properties must be any Number type and “Currency” must be out of four currency else throw validation exception. As you can created own Schema file base on the incoming input date.

 

trade-schema.json under /src/main/resources/schema folder

{
  "title": "Daily Trade Transaction",
  "description": "Daily Trade Transaction",
  "type": "object",
  "properties": {
    "id":{
      "type":"string"
    },
    "amount":{
      "type":"number"
    },
    "currency":{
      "type":"string",
      "enum":["INR", "HKD", "EUR", "USD"]
    }
  }
}

ref link:-
http://json-schema.org/examples.html
validate Schema online :-
http://json-schema-validator.herokuapp.com/

Let’s build a simple Application :-

trade.json :- Input data store in a file.

id,amount,currency
"1001",10000045.999,"EUR"
"1002",17777045.999,"HKD"
"1003",10000045.999,"USD"
"1004",1234045.999,"EUR"
"1005",100875.999,"HKD"
"1006",165780045.999,"EUR"
"1007",32452345.999,"INR"
"1008",7777777.999,"EUR"

 

JsonSchemaManager.Java : Used to validate all Java Object with specific Schema.


package com.example.utilities;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.RuntimeJsonMappingException;
import com.github.fge.jackson.JsonLoader;
import com.github.fge.jsonschema.core.exceptions.ProcessingException;
import com.github.fge.jsonschema.core.report.ProcessingMessage;
import com.github.fge.jsonschema.core.report.ProcessingReport;
import com.github.fge.jsonschema.main.JsonSchemaFactory;
import com.github.fge.jsonschema.main.JsonValidator;
import com.google.common.collect.Lists;

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

import static javafx.scene.input.KeyCode.J;

/**
 * Created by MYPC on 7/17/2016.
 */
public class JsonSchemaManager {
    private final JsonValidator validator = JsonSchemaFactory.byDefault().getValidator();
    private Map<Class<?>, JsonNode> jsonNodeMap = new HashMap<>();

    public void load(Class<?> className, String schema) throws IOException {
        JsonNode schemaFromDisk = JsonLoader.fromURL(this.getClass().getResource(schema));
        jsonNodeMap.put(className, schemaFromDisk);
    }

    public void check(Class<?> className, JsonNode toBeValidate) {

        ProcessingReport report = null;
        try {
            report = validator.validate(jsonNodeMap.get(className), toBeValidate);
            if (!report.isSuccess()) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(" Oops!! failed JSON validation ");
                stringBuilder.append(":").append("\n");
                List messages = Lists.newArrayList(report);

                for (int i = 0; i < messages.size(); i++) { stringBuilder.append("- "); stringBuilder.append(messages.get(i).toString()); stringBuilder.append((i == (messages.size()) - 1) ? "" : "\r"); } throw new RuntimeException(stringBuilder.toString()); } } catch (ProcessingException e) { throw new RuntimeJsonMappingException("ERROR -->" + e.toString());
        }
    }
}

Main Class that validate the JSON data.


package com.example;

import com.example.model.Transaction;
import com.example.service.CSVReader;
import com.example.utilities.JsonSchemaManager;
import com.fasterxml.jackson.databind.JsonNode;

import java.io.IOException;
import java.util.List;

/**
 * Created by MYPC on 7/18/2016.
 */
public class JSONSchemaReaderApp {

    public static void main(String[] args) throws IOException {

        JsonSchemaManager jsonSchemaManager = new JsonSchemaManager();
        CSVReader csvReader = new CSVReader();
        // Load schema file from resource folder.
        jsonSchemaManager.load(Transaction.class, "/schema/trade-schema.json");
        // Load JSON data from file system and convert into JsonNode Object
        List lists = csvReader.load(Transaction.class, JSONSchemaReaderApp.class.getClassLoader().getResource("trade.csv"));
        for (int i = 0; i < lists.size(); i++) {
            //validate each JsonNode of Type Transaction to Schema file.
            jsonSchemaManager.check(Transaction.class, lists.get(i));
            lists.get(i);
        }
    }
}

complete src download here

Thanks

Jackson JSON Java Parser Example

Posted on

Jackson JSON Parser API provides easy way to convert JSON to POJO Object and supports easy conversion to Map from JSON data. Jackson supports generics too and directly converts them from JSON to object.

we can add below dependency in your pom.xml.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-core -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.0</version>
</dependency>

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.8.0</version>
</dependency>

jackson-databind jar depends on jackson-core and jackson-annotations libraries, so if you are adding them directly to build path, make sure you add all three otherwise you will get a runtime error.

Below is the Utilities class that uses Jackson API to transform String to Json to Map object or any Java type object or vice-versa.   ThreadLocal is used here because ObjectMapper is not Thread’s safe in Multithreading app otherwise simply create a static variable of ObjectMapper.


package com.example.utilities;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

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

/**
 * Created by MYPC on 7/18/2016.
 */
public class JSONConverter {

    protected static final ThreadLocal OBJECT_MAPPER_THREAD_LOCAL = ThreadLocal.withInitial(() -> new ObjectMapper());

    /**
     * Convert String as JSON to JsonNode.
     *
     * @param payload
     * @return
     */
    public static JsonNode getJsonFromString(String payload) {
        try {
            return OBJECT_MAPPER_THREAD_LOCAL.get().readTree(payload);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Convert JsonNode Object to Map
     *
     * @param payload
     * @return
     */
    public static Map getMapFromJson(JsonNode payload) {
        try {
            return OBJECT_MAPPER_THREAD_LOCAL.get().readerFor(Map.class).readValue(payload);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Convert Map Object to JsonNode.
     *
     * @param payload
     * @return
     */
    public static JsonNode getJsonFromMap(Map payload) {
        try {
            return getJsonFromString(OBJECT_MAPPER_THREAD_LOCAL.get().writeValueAsString(payload));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * Create a Empty Object Node. i.e {}
     *
     * @return
     */
    public static ObjectNode createObjectNode() {
        return OBJECT_MAPPER_THREAD_LOCAL.get().createObjectNode();
    }

    /**
     * Create a Empty Array Json Object i.e [{},{}]
     *
     * @return
     */
    public static ArrayNode createArrayNode() {
        return OBJECT_MAPPER_THREAD_LOCAL.get().createArrayNode();
    }

    /**
     * Remove particular key elements from JsonNode.
     *
     * @param payload
     * @param key
     * @return
     */
    public static JsonNode remove(JsonNode payload, String key) {
        ((ObjectNode) payload).remove(key);
        return payload;
    }

    public static void main(String[] args) {
        String payload = "{\"id\":\"1001\", \"amount\":\"10000045.999\", \"currency\":\"EUR\"}";
        System.out.println(" Payload String  >> " + payload);
        JsonNode jsonNode = getJsonFromString(payload);
        System.out.println(" Convert String Payload to JsonNode  >> " + payload);
        Map map = getMapFromJson(getJsonFromString(payload));
        System.out.println(" GET Map Object from Payload String >> " + map);
        System.out.println(" Before Removing 'amount' from payload >> " + jsonNode);
        remove(jsonNode, "amount");
        System.out.println(" After Removing 'amount' from payload >> " + jsonNode);
        System.out.println(" Convert Map to JSON Node Object  >>" + getJsonFromMap(map));

        System.out.println(" Employee JsonNode >>" + createEmployeeJson());
        System.out.println(" Convert Employee Json to Map Object >>" + getMapFromJson(createEmployeeJson()));
    }

    /**
     * Testing on some real data.
     * employee.json
     * {
     * "id":"123",
     * "name":"Rahul Kumar",
     * "address":{
     *      "street":"Kalkaji",
     *      "city":"Delhi",
     *      "zipcode":"110020"
     * },
     * "phoneNumbers":[
     *      "9923456469",
     *      "9886786786"
     * ],
     * "role":"Developer"
     * }
     *
     * @return
     */
    private static JsonNode createEmployeeJson() {
        ObjectNode employeeJsonNode = createObjectNode();
        ObjectNode addressNode = createObjectNode();
        ArrayNode phoneList = createArrayNode();
        addressNode.put("street", "Kalkaji");
        addressNode.put("city", "Delhi");
        addressNode.put("zipcode", "110020");

        phoneList.add("9923456469");
        phoneList.add("9886786786");

        employeeJsonNode.put("id", "123");
        employeeJsonNode.put("name", "Rahul Kumar");
        employeeJsonNode.set("address", addressNode);
        employeeJsonNode.set("phoneNumbers", phoneList);
        employeeJsonNode.put("role", "Developer");
        return employeeJsonNode;
    }
}


output:-

Payload String >> {"id":"1001", "amount":"10000045.999", "currency":"EUR"}
 Convert String Payload to JsonNode >> {"id":"1001", "amount":"10000045.999", "currency":"EUR"}
 GET Map Object from Payload String >> {id=1001, amount=10000045.999, currency=EUR}
 Before Removing 'amount' from payload >> {"id":"1001","amount":"10000045.999","currency":"EUR"}
 After Removing 'amount' from payload >> {"id":"1001","currency":"EUR"}
 Convert Map to JSON Node Object >>{"id":"1001","amount":"10000045.999","currency":"EUR"}
 Employee JsonNode >>{"id":"123","name":"Rahul Kumar","address":{"street":"Kalkaji","city":"Delhi","zipcode":"110020"},"phoneNumbers":["9923456469","9886786786"],"role":"Developer"}
 Convert Employee Json to Map Object >>{id=123, name=Rahul Kumar, address={street=Kalkaji, city=Delhi, zipcode=110020}, phoneNumbers=[9923456469, 9886786786], role=Developer}

How to read CSV file in Java

Posted on

Jackson data format module for reading and writing CSV-encoded data, either as “raw” data (sequence of String arrays ) , or via data binding to/from Java Objects (POJOs).

To use this extension on Maven-based projects, use following dependency:

<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-csv</artifactId>
  <version>2.7.0</version>
</dependency>

Read CSV file based on Java Class.

AS below schema Java Object have explicitly defined Order and properties type to ensured that reading or writing the data in given order.


package com.example.model;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.annotation.JsonRootName;

import java.io.Serializable;
import java.math.BigDecimal;

/**
 * Created by MYPC on 7/18/2016.
 */
@JsonPropertyOrder(value = {"id", "amount", "currency"})
@JsonRootName("transaction")
public class Transaction implements Serializable {
    public enum Currency {
        INR, HKD, EUR, USD
    }
    @JsonProperty
    private String id;
    @JsonProperty
    @JsonFormat(shape = JsonFormat.Shape.NUMBER)
    private BigDecimal amount;
    @JsonProperty
    private Currency currency;

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public double getAmount() {
        return amount.doubleValue();
    }
    public void setAmount(BigDecimal amount) {
        this.amount = amount;
    }
    public Currency getCurrency() {
        return currency;
    }
    public void setCurrency(Currency currency) {
        this.currency = currency;
    }
    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("Transaction{");
        sb.append("id='").append(id).append('\'');
        sb.append(", amount=").append(amount);
        sb.append(", currency=").append(currency);
        sb.append('}');
        return sb.toString();
    }
}


Trade.csv  file reside in project “/src/main/resources” folder.

id,amount,currency
"1001",10000045.999,"EUR"
"1002",17777045.999,"HKD"
"1003",10000045.999,"USD"
"1004",1234045.999,"EUR"
"1005",100875.999,"HKD"
"1006",165780045.999,"EUR"
"1007",32452345.999,"INR"
"1008",7777777.999,"EUR"

 

Reading CSV file to Java Object.


package com.example;

import com.example.model.Transaction;
import com.fasterxml.jackson.dataformat.csv.CsvMapper;
import com.fasterxml.jackson.dataformat.csv.CsvSchema;

import java.io.IOException;
import java.util.List;
/**
 * Created by MYPC on 7/18/2016.
 */
public class JSONSchemaReaderApp {

    public static void main(String[] args) throws IOException {

        CsvMapper csvMapper = new CsvMapper();
        CsvSchema csvSchema = csvMapper.typedSchemaFor(Transaction.class).withHeader();
        List list = new CsvMapper().readerFor(Transaction.class)
                .with(csvSchema.withColumnSeparator(CsvSchema.DEFAULT_COLUMN_SEPARATOR))
                .readValues(JSONSchemaReaderApp.class.getClassLoader().getResource("trade.csv"))
                .readAll();
        for (int i = 0; i < list.size(); i++) {
            System.out.printf(" Transaction Row [%d] : %s \n", i + 1, list.get(i));
        }
    }
}


Output:-

Transaction Row [1] : Transaction{id='1001', amount=10000045.999, currency=EUR}
Transaction Row [2] : Transaction{id='1002', amount=17777045.999, currency=HKD}
Transaction Row [3] : Transaction{id='1003', amount=10000045.999, currency=USD}
Transaction Row [4] : Transaction{id='1004', amount=1234045.999, currency=EUR}
Transaction Row [5] : Transaction{id='1005', amount=100875.999, currency=HKD}
Transaction Row [6] : Transaction{id='1006', amount=165780045.999, currency=EUR}
Transaction Row [7] : Transaction{id='1007', amount=32452345.999, currency=INR}
Transaction Row [8] : Transaction{id='1008', amount=7777777.999, currency=EUR}

Reading CSV file into Map


public static void main(String[] args) throws IOException {
        CsvMapper csvMapper = new CsvMapper();

        CsvSchema csvSchema = csvMapper.typedSchemaFor(Map.class).withHeader();
        MappingIterator<Map<String, String>> it = csvMapper.readerFor(Map.class).with(csvSchema.withColumnSeparator(CsvSchema.DEFAULT_COLUMN_SEPARATOR))
                .readValues(JSONSchemaReaderApp.class.getClassLoader().getResource("trade.csv"));
        List<Map<String, String>> listOfMapSchema = it.readAll();

        for (Map<String, String> map : listOfMapSchema) {
            System.out.println(map);
        }

    }

output:-

{id=1001, amount=10000045.999, currency=EUR}
{id=1002, amount=17777045.999, currency=HKD}
{id=1003, amount=10000045.999, currency=USD}
{id=1004, amount=1234045.999, currency=EUR}
{id=1005, amount=100875.999, currency=HKD}
{id=1006, amount=165780045.999, currency=EUR}
{id=1007, amount=32452345.999, currency=INR}
{id=1008, amount=7777777.999, currency=EUR}

Java 8 – Sorted Map By Key & Value

Posted on

Java-8

 

 

 

Below example will show, how to sort Collection & Map element by Key & Value using Lambda Expression in Java 8.

Example 1

In this example, we will see how to sort  element of Collection using Lambda expression.


        List listOfString = new ArrayList<>();
        listOfString.add("Z");
        listOfString.add("Q");
        listOfString.add("D");
        listOfString.add("A");
        listOfString.add("H");
        listOfString.add("T");

        listOfString.stream().sorted((e1,e2)->e1.compareTo(e2)).forEach(e->{
            System.out.println(" sorted list of String "+e);
        });
        // return new sorted list.
        /*        
        listOfString = listOfString.stream()
                                   .sorted((e1,e2)->e1.compareTo(e2))
                                   .collect(Collectors.toList());
        listOfString.forEach(e->{
            System.out.println(" sorted list of String "+e);
        });*/

Output:-
sorted list of String A
sorted list of String D
sorted list of String H
sorted list of String Q
sorted list of String T
sorted list of String Z

Example 2 : See how to sort a List’s Person by Name.

 


        List list = new ArrayList();

        list.add(new Person(6, "FF", 13, Person.SEX.MALE, "GOA"));
        list.add(new Person(7, "GG", 31, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(8, "HH", 30, Person.SEX.MALE, "Mumbai"));
        list.add(new Person(9, "II", 22, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(1, "AA", 12, Person.SEX.FEMALE, "Delhi"));
        list.add(new Person(2, "BB", 22, Person.SEX.FEMALE, "MP"));
        list.add(new Person(3, "CC", 44, Person.SEX.FEMALE,"UP"));
        list.add(new Person(4, "DD", 25, Person.SEX.MALE, "Gurgaon"));
        list.add(new Person(5, "EE", 51, Person.SEX.FEMALE, "GOA"));

         // sorted Person by name
        List sortedList = list.stream()
                .sorted((p1,p2)->p1.getName().compareTo(p2.getName()))
                .collect(Collectors.toList());
        sortedList.forEach(p->System.out.println("sorted by name :: "+p.toString()));


output :-
sorted by name :: Person{id=1, name=’AA’, age=12, gender=FEMALE, location=’Delhi’}
sorted by name :: Person{id=2, name=’BB’, age=22, gender=FEMALE, location=’MP’}
sorted by name :: Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’UP’}
sorted by name :: Person{id=4, name=’DD’, age=25, gender=MALE, location=’Gurgaon’}
sorted by name :: Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’GOA’}
sorted by name :: Person{id=6, name=’FF’, age=13, gender=MALE, location=’GOA’}
sorted by name :: Person{id=7, name=’GG’, age=31, gender=FEMALE, location=’Delhi’}
sorted by name :: Person{id=8, name=’HH’, age=30, gender=MALE, location=’Mumbai’}
sorted by name :: Person{id=9, name=’II’, age=22, gender=FEMALE, location=’Delhi’}

Example 3:- See how to sort a Map by value element


        //Sort a Map by their Value.
        Map<Integer, String> random = new HashMap<Integer, String>();
       
        random.put(1,"z");
        random.put(6,"k");
        random.put(5,"a");
        random.put(3,"f");
        random.put(9,"c");

        Map<Integer, String> sortedMap =
                random.entrySet().stream()
                        .sorted(Map.Entry.comparingByValue())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                (e1, e2) -> e2, LinkedHashMap::new));
        System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));

Output :-
Sorted Map: [5=a, 9=c, 3=f, 6=k, 1=z]

Example 4:- See how to sort a Map by Key element


        //Sort a Map by their Key.
        Map<Integer, String> random = new HashMap<Integer, String>();
       
        random.put(1,"z");
        random.put(6,"k");
        random.put(5,"a");
        random.put(3,"f");
        random.put(9,"c");

        Map<Integer, String> sortedMap =
                random.entrySet().stream()
                        .sorted(Map.Entry.comparingByKey())
                        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                                (e1, e2) -> e2, LinkedHashMap::new));
        System.out.println("Sorted Map: " + Arrays.toString(sortedMap.entrySet().toArray()));

Output :-
Sorted Map: [1=z, 3=f, 5=a, 6=k, 9=c]

Example 5:-

Here, A Map<String,Person> is created where String & Person object are taken as a Key & Value elements. First we will sort by Key elements then sort by Value elements in this below example.

Sorted by Map’s Key –


        Map<String,Person> map = new HashMap<>();
        map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
        map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
        map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));

        Map<String,Person> sortedNewMap = map.entrySet().stream()
                .sorted((e1,e2)->e1.getKey().compareTo(e2.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (e1, e2) -> e1, LinkedHashMap::new));
        sortedNewMap.forEach((key,val)->{
            System.out.println(key+ " = "+ val.toString());
        });

Output:- 

a = Person{id=4, name=’DD’, age=25, gender=MALE, location=’D’}
e = Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’B’}
g = Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’A’}

Final output give us a Map which values are sorted location field –


        Map<String,Person> map = new HashMap<>();
        map.put("g",new Person(5, "EE", 51, Person.SEX.FEMALE, "A"));
        map.put("a",new Person(4, "DD", 25, Person.SEX.MALE, "D"));
        map.put("e",new Person(3, "CC", 44, Person.SEX.FEMALE,"B"));

        Map<String,Person> sortedNewMap = map.entrySet().stream().sorted((e1,e2)->
                e1.getValue().getLocation().compareTo(e2.getValue().getLocation()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
                        (e1, e2) -> e1, LinkedHashMap::new));
        sortedNewMap.forEach((key,val)->{
            System.out.println(key+ " = "+ val.toString());
        });

Output:- 
g = Person{id=5, name=’EE’, age=51, gender=FEMALE, location=’A’}
e = Person{id=3, name=’CC’, age=44, gender=FEMALE, location=’B’}
a = Person{id=4, name=’DD’, age=25, gender=MALE, location=’D’}

 

There are lots of ways to do this work depends on the requirement. Hope you enjoy this post.
Thanks
——–

Java 8 – Predicate Example

Posted on Updated on

Java-8

 

 

 

Predicate:-

Predicates represent single argument functions that return a boolean value. It can be applied to any Collection/group of similar Objects that is evaluated by a Predicate  condition.

A Predicate is a Functional Interface,we can pass lambda expressions wherever predicate is expected. Although Predicate is not only a Functional Interface in Java 8 but a set of standard  Functional Interfaces are given for developer in Java 8 as below :-

  • Predicate: A property of the object passed as argument
  • Consumer: An action to be performed with the object passed as argument
  • Function: Transform a T to a U
  • Supplier: Provide an instance of a T (such as a factory)
  • UnaryOperator: A unary operator from T -> T
  • BinaryOperator: A binary operator from (T, T) -> T

Below is simple defined Predicate  by inline lambda expression:-


Predicate checkFemale = (p)->p.getGender()==SEX.FEMALE;
Predicate checkMale = (p)->p.getGender()==SEX.MALE;
Predicate checkJuniorMalePerson = (p)->p.getGender()==SEX.MALE && p.getAge() <=18;
Predicate checkSeniorFemalePerson = (p)->p.getGender()==SEX.FEMALE && p.getAge() > 18;
Predicate checkNCRRegionPerson = (p) -> p.getLocation().equalsIgnoreCase("Delhi") 
					|| p.getLocation().equalsIgnoreCase("Noida")
					|| p.getLocation().equalsIgnoreCase("Gurgaon");

 

In the below example,  We have a list of Employee Object having some pre-defined properties and base on a condition or set of conditions, group of Objects get evaluated.



import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import com.example.model.Person.SEX;

public class PersonPredicateTest {

	public static void main(String args[]) {
		Person person1 = new Person(1, "AA", 12, SEX.FEMALE, "Delhi");
		Person person2 = new Person(2, "BB", 22, SEX.FEMALE, "MP");
		Person person3 = new Person(3, "CC", 44, SEX.MALE, "UP");
		Person person4 = new Person(4, "DD", 25, SEX.MALE, "Gurgaon");
		Person person5 = new Person(5, "EE", 51, SEX.FEMALE, "GOA");
		Person person6 = new Person(6, "FF", 13, SEX.MALE, "GOA");
		Person person7 = new Person(7, "GG", 31, SEX.FEMALE, "Delhi");
		Person person8 = new Person(8, "HH", 30, SEX.MALE, "Mumbai");
		Person person9 = new Person(9, "II", 22, SEX.FEMALE, "Delhi");

		List listOfEmployee = new ArrayList<>(Arrays.asList(
				new Person[] { person1, person2, person3, person4, person5, person6, person7, person8, person9 }));

		// Get All Junior Female
		System.out.println("############ Get All Female ##############");
		process(listOfEmployee, checkFemale()).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Junior Female
		System.out.println("############ Get All Female ##############");
		process(listOfEmployee, checkMale()).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Junior Person who is living in NCR Region
		System.out.println("############ Get All Junior Person who is living in NCR Region ##############");
		process(listOfEmployee, checkJuniorPerson().and(checkNCRRegionPerson())).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Junior Female
		System.out.println("############ Get All Junior Female ##############");
		process(listOfEmployee, checkJuniorPerson().and(checkFemale())).forEach(p -> {
			System.out.println(p.toString());
		});
		// Get All Junior Male
		System.out.println("############ Get All Junior Male ##############");
		process(listOfEmployee, checkJuniorPerson().and(checkMale())).forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Delhi Regional Senior Person
		System.out.println("############ Get All Delhi Regional Senior Person ##############");
		Collection listOfDelhiRegionPerson = process(listOfEmployee,
				checkSeniorPerson().and(checkRegion("delhi")));
		listOfDelhiRegionPerson.forEach(p -> {
			System.out.println(p.toString());
		});

		// Get All Senior Female
		System.out.println("############ Get All Senior Female ##############");
		process(listOfEmployee, checkSeniorPerson().and(checkFemale())).forEach(p -> {
			System.out.println(p.toString());
		});
		// Get All Senior Male
		System.out.println("############ Get All Senior Male ##############");
		process(listOfEmployee, checkSeniorPerson().and(checkMale())).forEach(p -> {
			System.out.println(p.toString());
		});

	}

	private static Predicate checkJuniorPerson() {
		return (p) -> p.getAge() <= 18;
	}

	private static Predicate checkSeniorPerson() {
		return (p) -> p.getAge() > 18;
	}

	private static Predicate checkNCRRegionPerson() {
		return (p) -> p.getLocation().equalsIgnoreCase("Delhi") 
				|| p.getLocation().equalsIgnoreCase("Noida")
				|| p.getLocation().equalsIgnoreCase("Gurgaon");
	}

	private static Predicate checkMale() {
		return (p) -> p.getGender() == SEX.MALE;
	}

	private static Predicate checkRegion(String location) {
		return (p) -> p.getLocation().equalsIgnoreCase(location);
	}

	private static Predicate checkFemale() {
		return (p) -> p.getGender() == SEX.FEMALE;
	}

	public static  Collection process(Collection collection, Predicate predicate) {
		return collection.stream().filter(predicate).collect(Collectors. toList());
	}

}


Person.Java


public class Person {

	public enum SEX {
		MALE, FEMALE
	}

	private long id;
	private String name;
	private int age;
	private SEX gender;
	private String location;
        // Constructor here
        // Getter && Setter ....

Output :

############ Get All Female ##############
Person [id=1, name=AA, age=12, gender=FEMALE, location=Delhi]
Person [id=2, name=BB, age=22, gender=FEMALE, location=MP]
Person [id=5, name=EE, age=51, gender=FEMALE, location=GOA]
Person [id=7, name=GG, age=31, gender=FEMALE, location=Delhi]
Person [id=9, name=II, age=22, gender=FEMALE, location=Delhi]
############ Get All Female ##############
Person [id=3, name=CC, age=44, gender=MALE, location=UP]
Person [id=4, name=DD, age=25, gender=MALE, location=Gurgaon]
Person [id=6, name=FF, age=13, gender=MALE, location=GOA]
Person [id=8, name=HH, age=30, gender=MALE, location=Mumbai]
############ Get All Junior Person who is living in NCR Region ##############
Person [id=1, name=AA, age=12, gender=FEMALE, location=Delhi]
############ Get All Junior Female ##############
Person [id=1, name=AA, age=12, gender=FEMALE, location=Delhi]
############ Get All Junior Male ##############
Person [id=6, name=FF, age=13, gender=MALE, location=GOA]
############ Get All Delhi Regional Senior Person ##############
Person [id=7, name=GG, age=31, gender=FEMALE, location=Delhi]
Person [id=9, name=II, age=22, gender=FEMALE, location=Delhi]
############ Get All Senior Female ##############
Person [id=2, name=BB, age=22, gender=FEMALE, location=MP]
Person [id=5, name=EE, age=51, gender=FEMALE, location=GOA]
Person [id=7, name=GG, age=31, gender=FEMALE, location=Delhi]
Person [id=9, name=II, age=22, gender=FEMALE, location=Delhi]
############ Get All Senior Male ##############
Person [id=3, name=CC, age=44, gender=MALE, location=UP]
Person [id=4, name=DD, age=25, gender=MALE, location=Gurgaon]
Person [id=8, name=HH, age=30, gender=MALE, location=Mumbai]

Difference between List, List<E>, List<Object>, and List<?> in java

Posted on

java-logoThis is very important topics in Generic to know the difference between List, List<?>,  List<E>, and List<Object>. Enabling Generic in you application code provides you a flexibility of code to work on different type of Data type and ensure to Type safety and easy to read.

In this example, we took a Collection Type i.e List but it can be any Collection Type i.e Set, LinkedList  and Map.

 

List

It’s a raw type and not type safe. It will generate a Runtime exception when casting is bad.


                List list = new ArrayList();
		list.add("Hello");
		list.add(234);
		list.add(new Object());
		// explicitly cast require here
		String s = (String) list.get(0);

 

List<E>

It’s a parameterized type and ‘E‘ can be referred to any non-primitive type, any class type, any interface type, any array type, or even another type variable.


public <E> List<E> unmodifiableList(List<E> list) {
  Collections.unmodifiableList(list);
  return list;
 }

E i.e element can be replaced with some concrete type like String,Integer,Number and other class, interface type.

List<Object>

It is a parameterized type of Object and It’s only allowed to add Object sub-type But does not allow to assign the sub-type reference into that list- means List<Object> instance will not accept the references of List<String> because List<String> is not a subtype of List<Object>, therefore compile generate a compiler errors.


List<Object> listOfObject = new ArrayList<Object>();
listOfObject.add("Hello");
listOfObject.add(234);
// OK
Object o = listOfObject.get(0);

List<String> listOfString = new ArrayList<String>();
listOfString.add("Hi");
//Error :- Type mismatch: cannot convert from List<String> to List<Object>
listOfObject = listOfString; // Compiler time error - Bad casting
List<Object> list1 = listOfString; // Compiler time error - Bad casting

List<Object> list2 = list1; // OK

List<?>

‘?’ Question marks represented an unknown type. List<?> can be something that we don’t know right now. It’s also considered as READ-ONLY list where no any write operation will be performed only read operation is allowed like iteration over it, sizes of list and etc.

List<?> listOnUnknow = new ArrayList();
listOnUnknow.addAll("hello"); // Error because compiler don't know what type of value is going to store here.

We can do it like this :-


public static void reverse(List<?> list) {
     int size = list.size();
     if (size < REVERSE_THRESHOLD || list instanceof RandomAccess) {
        for (int i=0, mid=size>>1, j=size-1; i<mid; i++, j--)
           swap(list, i, j);
     } else {
    ListIterator fwd = list.listIterator();
    ListIterator rev = list.listIterator(size);
    for (int i=0, mid=list.size()>>1; i<mid; i++) {
    Object tmp = fwd.next();
    fwd.set(rev.previous());
    rev.set(tmp);
}
}
}

Thanks