Sunday, November 14, 2021

JavaScript Character to ASCII Using String.charCodeAt() Function

1. Overview

In this tutorial, we will learn how to use the String object charCodeAt() function in javascript.

String.charCodeAt() function is used to convert the character to ascii code.

This method returns the integer value that is in the range from 0 to 65535 representing the UTF 16 standard code.

2. Syntax of String.charCodeAt()


Below is the syntax
charCodeAt(index)
Unicode points range from 0 to 1114111. The first 128 codes denote the ascii characters.

Sunday, August 16, 2020

Java 8 Stream Sorting Multiple Fields Examples

Example to sort the stream on multiple fields using Comparaor.comparing() and Comparator.thenComparing() methods in java 8.

The below program is to sort the Employee list on name and age properties.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class SortMultipleFieldsSorted {

    public static void main(String[] args) {


        Employee e1 = new Employee(111, "Hari", 30);
        Employee e2 = new Employee(222, "Jool", 35);
        Employee e3 = new Employee(333, "Hari", 28);
        Employee e4 = new Employee(444, "Jool", 23);

        List<Employee> unsortredList = Arrays.asList(e1, e2, e3, e4);

        Comparator<Employee> idEmployeeComparator = Comparator.comparing(Employee::getName);

        Comparator<Employee> titleEmployeeComparator = Comparator.comparing(Employee::getAge);

        Comparator<Employee> multipleFieldsComparator = idEmployeeComparator.thenComparing(titleEmployeeComparator);

        System.out.println("Unsorted Emp List : ");

        for (Employee e : unsortredList) {
            System.out.println(e);
        }

        List<Employee> sortedList1 = unsortredList.stream().sorted(multipleFieldsComparator).collect(Collectors.toList());

        System.out.println("After sorting books list : ");


        for (Employee e : sortedList1) {
            System.out.println(e);
        }


        List<Employee> unsortredEmpList2 = Arrays.asList(e1, e2, e3, e4);

        System.out.println("Unsorted Books List 2 : ");
        for (Employee e : unsortredEmpList2) {
            System.out.println(e);
        }

        List<Employee> sortedList2 = unsortredEmpList2.stream().sorted(multipleFieldsComparator).collect(Collectors.toList());

        System.out.println("After sorting emp list 2: ");


        for (Employee e : sortedList2) {
            System.out.println(e);
        }
    }
}

class Employee {

    private int id;
    private String name;
    private int age;

    public Employee(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Employee{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Output:

Unsorted Emp List : 
Employee{id=111, name='Hari', age=30}
Employee{id=222, name='Jool', age=35}
Employee{id=333, name='Hari', age=28}
Employee{id=444, name='Jool', age=23}
After sorting books list : 
Employee{id=333, name='Hari', age=28}
Employee{id=111, name='Hari', age=30}
Employee{id=444, name='Jool', age=23}
Employee{id=222, name='Jool', age=35}
Unsorted Books List 2 : 
Employee{id=111, name='Hari', age=30}
Employee{id=222, name='Jool', age=35}
Employee{id=333, name='Hari', age=28}
Employee{id=444, name='Jool', age=23}
After sorting emp list 2: 
Employee{id=333, name='Hari', age=28}
Employee{id=111, name='Hari', age=30}
Employee{id=444, name='Jool', age=23}
Employee{id=222, name='Jool', age=35}


Comparaor.comparing()

Saturday, August 15, 2020

Java 8 Convert All Map Keys and Values into List

Java 8 Example to Convert All Map Keys and Values into List

Use keyset().stream() and call collect() method to convert into List.

Use values().stream() and call collect() method to convert into List.

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Java8MapToListExample {

    public static void main(String[] args) {

        Map<Integer, String> numbers = new HashMap<>();

        numbers.put(10, "ten");
        numbers.put(20, "twenty");
        numbers.put(30, "thirty");
        numbers.put(40, "forty");
        numbers.put(50, "fifty");

        //java 8 - convert all keys to map
        List<Integer> keysList = numbers.keySet().stream().collect(Collectors.toList());

        System.out.println("Map keys List :");

        for (Integer integer : keysList) {
            System.out.println(integer);
        }

        // java 8 - convert all keys to map
        List<String> valuesList = numbers.values().stream().collect(Collectors.toList());

        System.out.println("Map values list :");

        for (String s : valuesList) {
            System.out.println(s);
        }

        System.out.println("removing odd even fruit id's as list : ");

        List<Integer> evenList = numbers.keySet().stream().filter(id -> id % 2 == 0).collect(Collectors.toList());
        evenList.forEach(id -> System.out.println(id));
    }
}

Output:


Map keys List :
50
20
41
10
30
Map values list :
fifty
twenty
forty one
ten
thirty
removing odd even fruit id's as list : 
50
20
10
30


Java 8 Stream.iterate() VS Stream.random() - Infinite Streams


import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamGenerateVSIterate {

    public static void main(String[] args) {

        // Example to generate 10 random numbers from 0 to 20.
        Supplier<Integer> infiniteStream1 = () -> new Random().nextInt(20);

        List<Integer> randomNumbers = Stream.generate(infiniteStream1).limit(15).collect(Collectors.toList());

        System.out.println("10 random numbers list : " + randomNumbers);

        // Example to generate 10 random numbers from 0 to 20.
        Stream<Integer> infiniteStream2 = Stream.iterate(0, i -> i + 1);

        List<Integer> first10Numbers = infiniteStream2.limit(15).collect(Collectors.toList());

        System.out.println("first 10 numbers list : " + first10Numbers);

    }
}

Output:

15 random numbers list : [18, 3, 11, 4, 11, 5, 19, 3, 4, 5, 11, 7, 6, 0, 0]
first 15 numbers list : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]



Java 8 Stream.generate() - Generate Random UUID numbers from Infinite Series

 

package com.javaprogramto.java8.streams.infinite;

import java.util.List;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamGenerateExample {

    public static void main(String[] args) {

        // Generates the UUID
        Supplier<UUID> randomUUIDSupplier = () -> UUID.randomUUID();

        List<UUID> uuidList = Stream.generate(randomUUIDSupplier).limit(15).collect(Collectors.toList());

        System.out.println("10 random UUID list : "+uuidList);

    }
}

Output:

10 random UUID list : 

[781bce19-1dfd-4564-b220-80fb7aa850bc, a24d411a-7d5a-4447-9f5b-77f366dfd853, ccfd492e-78a4-47f7-9941-366cd60368c7, 3a97b09d-5e47-4814-8075-098ed516572d, 3ea7aaaf-04b9-4a12-b97c-e32e0ac0db80, d98690b7-696f-4355-b1e8-ce381378f490, 173d0497-dd8f-401f-8d39-30b2ddca8cf4, 7880e981-3265-4ebf-a73e-0c706c5b21f6, ac255ce3-a964-4d15-bf9c-13b5834cbc88, 6aa279ee-32b7-4e14-b689-d1586b8b124a, 0e1dd672-99d1-498d-93cf-1ddefb9bfc34, d9dd7643-83c9-44cb-a669-483e1e6c877e, 98f3018f-a7c1-4dbb-b391-8a1d2885553a, aa75f989-01e3-4b15-93ab-5096068f26a4, ad762c3b-9a66-438a-801c-8e3c48f8a223]



Java 8 Stream.iterate() Infinite Streams Example

Java 8 Example program to generate the first 10 numbers from the infinite stream using Stream.iterate()Method


package com.javaprogramto.java8.streams.infinite;

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

public class StreamIterateExample {

    public static void main(String[] args) {

        // Creating a infinite Stream
        Stream<Integer> integerInfiniteStream = Stream.iterate(1, i -> i +1);

        List<Integer> first10Numbers = integerInfiniteStream.limit(10).collect(Collectors.toList());

        System.out.println("integerInfiniteStream with limit 10 : "+first10Numbers);

    }
}

Output:

integerInfiniteStream with limit 10 : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Java 8 Example program to generate the 10 ten even numbers from the infinite stream using Stream.iterate()Method


package com.javaprogramto.java8.streams.infinite;

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

public class StreamIterateExample {

    public static void main(String[] args) {

        // Creating a infinite Stream
        Stream<Integer> even10Numbers = Stream.iterate(0, i -> i +2);

        List<Integer> first10Numbers = even10Numbers.limit(10).collect(Collectors.toList());

        System.out.println("even10Numbers with limit 10 : "+first10Numbers);

    }
}

Output:

even10Numbers with limit 10 : [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]



Tuesday, April 14, 2020

Java 8 flatMap Examples - Stream flatmap convert Stream<List<List<String>>> into Stream<String>

1. Introduction


In this article, We'll learn about java 8 new Stream API flatMap() method. When to use it and how to use it.

flatMap() method is used to convert or flatten Stream of collections into Stream of collection values by removing the collection.

Removing collection such as List or Set from Stream is called flattening.

FlatMap() is part of Stream Intermediate Operations in Java 8.

Java 8, Stream can hold any type of collections and can be converted into Stream<T> as below.

Stream<List<List<String>>> --> apply flatMap() logic --> Stream<String>
Stream<Set<Set<String>>> --> apply flatMap() logic --> Stream<String>
Stream<List<String>>> --> apply flatMap() logic --> Stream<String>
Stream<List<Object>>> --> apply flatMap() logic --> Stream<Object>


Sunday, April 12, 2020

Java 8 Optional orElseThrow() Example | Throw Exception in Optional in Java 8

1. introduction


In this tutorial, We'll learn how to throw an exception if the option is empty. Optional API orElseThrow() method returns value from Optional if present. Otherwise, it will throw the exception created by the Supplier.

2. Syntax


public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier)
                                    throws X extends Throwable


Return the contained value, if present, otherwise throw an exception to be created by the provided supplier.

A method reference to the exception constructor with an empty argument list can be used as the supplier. For example, IllegalStateException::new, ArithmeticException::new

Java 8 Optional orElseGet() Example

1. Introduction

In this tutorial, We'll learn java 8 Optional API orElseGet() method examples and where to use.

2. Syntax

[lock]
public T orElseGet(Supplier<? extends T> other)

Return the value if present, otherwise invoke other and return the result of that invocation. This method takes the Supplier Functional Interface. [/lock]

if the Supplier is null, it throws NullPointerException.


Wednesday, September 11, 2019

Java 8 Optional ifPresent() - Working Example

1. Overview


In this tutorial, We'll learn how to perform an action if a value is present in Optional. Java 8 Optional ifPresent() does the job for us.

Instead of directly getting the value using get() method, first, it checks the condition value != null.

java-8-optional-ifpresent


The old way is done using the isPresent() method as below. But, ifPresent is much simplified than isPresent().

Java 8: How to Get the Last Element of a Stream in Java?

$type=blogging

1. Introduction

[post_ads]

in this tutorial, We will be looking at different ways to get the last element of a Stream in Java 8.

When we work with Stream then we have to go through one by one element of Stream. But, if we want to get directly last value and ignore the remaining preceding elements.

here are the possible ways to retrieve only the last value from the stream.

2. Using reduce() method

[lock]
reduce() method is part of the Stream API and we have to pass the lambda expression with two arguments. [/lock]

Syntax:


Optional reduce​(BinaryOperator accumulator)


Monday, August 26, 2019

StringBuffer VS StringBuilder in Java

1. Overview


In this tutorial, We'll be learning differences between the StringBuffer and StringBuilder in java. First, let us take a brief introduction to both and see the differences.

StringBuffer is introduced in java api first and then

2. StringBuffer


This is a thread-safe, mutable sequence of characters. A string buffer is just like a String, but it can be modified using its methods such as insert() or append() methods.

This class is a thread-safe and it can be shared among multiple threads.

Thursday, August 22, 2019

Java Examples to Create New Empty File and A Temporary File

1. Overview


In this tutorial, We'll be learning how to create a file in java and how to create a temp file in java.

Example programs demonstrated in the following methods.

createNewFile()
createTempFile()

Example Programs on Files

createNewFile() method is used to create a new empty file.
createTempFile() method is used to create a temporary file.

Java Examples To Work With Properties File (Read & Write)

1. Overview


In this tutorial, We'll be learning how to read from and write to the properties file in java.

Java API priovides a class Properties which is part of java.util package.

The Properties class stores the set of key, value pairs as properties. It internally stores all properties in a Stream. The Properties can be saved to a stream or loaded from a stream. Each key and its corresponding value in the property list stored as a string.

public class Properties
extends Hashtable<Object,​Object>

Properties inherit from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead.

Java Program to Convert Degree Celsius to Kelvin & Kelvin to Celsius

1. Overview


In this tutorial, We'll learn how to convert Degree Celsius to kelvin in Java programming language. First, we will learn the formula and temperature conversion programs in java.

Degree celsius and kelvin are part of temparature mesures.

The formula for conversion:

K = ( °C + 273.15 )

Where K is kelvin and °C is degree celsius

Example 1:

Celsius: 100
Kelvin: 373.15

Example 2:

Celsius: 120
Kelvin: 393.15

Wednesday, August 21, 2019

Java - String to Int Conversion Examples

1. Overview


In this tutorial, We'll learn to convert String to integer in java.

We will be showing the example programs using the following methods and possible exceptions that occur at runtime.

Integer.parseInt()
Integer.valueOf()

For Example, We have a string "456" and want it to convert int type.

Tuesday, August 20, 2019

Java 8 Streams filter() - Working Examples

1. Overview


In this tutorial, We'll learn about the new Java 8 Streams API filter() method. This filter method is the one mostly used in streams. Streams build the operations sequentially and parallel.

filter() method takes Predicate which holds a condition. If the condition is true then this element is passed to the next operation in the stream.


We will discuss with example programs so that you can understand clearly.

First, will talk about syntax, examples and how it works internally.

Friday, August 16, 2019

Java 8 StreamSupport Examples

1. Overview


In this tutorial, We'll be learning Java 8 StreamSupport class methods with example programs. Let us see its syntax and how to convert iterable to Stream using StreamSupport.stream() method. This class is part of java.util.stream package.

Core methods of StreamSupport class are stream(), intStream(), doubleStream(), longStream().

Thursday, August 15, 2019

Java 8 MinguoDate API Examples

1. Overview


In this tutorial, We'll be learning MinguoDate introduced in Java 8. The MinguoDate class is immutable and thread-safe. So, it can be used in multithreaded applications without explicit synchronization.

This date operates using the Minguo calendar. This calendar system is primarily used in the Republic of China, often known as Taiwan. Dates are aligned such that 0001-01-01 (Minguo) is 1912-01-01 (ISO).

Below is the class MinguoDate internal declaration in API source code.

public final class MinguoDate
extends Object
implements ChronoLocalDate, Serializable


Now, We'll see the example programs to convert localdate to MinguoDate and from MinguoDate to local date.

Wednesday, August 14, 2019

Java 8 Files walk() Examples

1. Overview


In this tutorial, We'll be learning the Files API walk() method in java 8. walk() method is part of the Files class and java.nio.file package.

This method is used to walk through any given directory and retrieves Stream<Path> as the return value. This method traverses through all its subdirectories as well.

API Description:

Return a Stream that is lazily populated with Path by walking the file tree rooted at a given starting file. The file tree is traversed depth-first, the elements in the stream are Path objects that are obtained as if by resolving the relative path against start.

Note: This method must be used within a try-with-resources statement.

In this article, We'll see its syntax and example programs on how to list all the files in the directory, list directories and specific file patterns such as .csv or file name contains 'Match' word.