Tuesday, June 15, 2021

Spring Boot - How to Change Default Port in Spring Application?

1. Introduction

In this tutorial, You'll learn how to change the default port to new custom port in Spring Boot application.

Spring Boot by default does many auto configurations and provides the ways to customize as per the need.

The most common use case is changing the port of application to the new one. Because by default embedded tomcat is configured with 8080 port. If you already another service that is running on the same port then you can not start a new service on that port. So, you must have to run the application on a different port. 

Changing the port can be done in many possible ways.

Let us see one be one with practical example programs.

Monday, June 14, 2021

Kotlin - Convert Map to List Examples

1. Overview

In this tutorial, We will learn how to convert the Map to List in kotlin programming. Map implementations such as HashMap or TreeMap can be converted into an ArrayList or List object.

Let us explore the different ways to do conversion from map to get the list of keys and values.

Kotlin - Convert Map to List Examples



2. Converting HashMap to List in Kotlin Using ArrayList Constructor


This approach is the simple one and easy. First create the HashMap object with HashMap() constructor
Next, adding few key value pairs to the map. Use map.keys and map.values to get the all keys and values.
pass these values to ArrayList constructor to convert the map to list.

These properties will be invoking the below functions internally when you are using java.util.HashMap.

map.keys --> map.keySet()
map.values --> map.values()

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    var map = HashMap<Int, String>();

    map.put(10, "Ten")
    map.put(20, "Twenty")
    map.put(30, "Thirty")
    map.put(40, "Fourty")
    map.put(50, "Fifty")

    var keysList = ArrayList(map.keys);
    var valuesList = ArrayList(map.values);

    println("Keys list : $keysList")
    println("Values list : $valuesList")

}

Output:
Keys list : [50, 20, 40, 10, 30]
Values list : [Fifty, Twenty, Fourty, Ten, Thirty]

3. Converting LinkedHashMap to List in Kotlin Using ArrayList Constructor


From the above program, the output is not in the order what is inserted into the map. To preserve the insertion order then need to use LinkedHashMap class instead of HashMap.

Look at the below program and observer the output order.

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    // to holds the insertion order
    var map = LinkedHashMap<Int, String>();

    map.put(10, "Ten")
    map.put(20, "Twenty")
    map.put(30, "Thirty")
    map.put(40, "Fourty")
    map.put(50, "Fifty")

    // gets the keys and values as per the insertion
    var keysList = ArrayList(map.keys);
    var valuesList = ArrayList(map.values);

    // prints
    println("Keys list : $keysList")
    println("Values list : $valuesList")
}
Output:
Keys list : [10, 20, 30, 40, 50]
Values list : [Ten, Twenty, Thirty, Fourty, Fifty]


4. Kotlin Map to List using toList() method


Use toList() method on map object or keys, values properties.

package com.javaprogramto.kotlin.collections.map.list
import java.util.HashMap

fun main(array: Array<String>) {

    var map = HashMap<Int, String>();

    map[10] = "Ten"
    map[20] = "Twenty"
    map[30] = "Thirty"
    map[40] = "Fourty"
    map[50] = "Fifty"

    // example 1 using toList() method
    var keysList = map.keys.toList();
    var valuesList = map.values.toList();
    println("using toList()")
    println("Keys list : $keysList")
    println("Values list : $valuesList")

    // example 2 using toList() method

    var mutableMap: MutableMap<Int, String> = HashMap()
    mutableMap[10] = "Ten"
    mutableMap[20] = "Twenty"
    mutableMap[30] = "Thirty"
    mutableMap[40] = "Fourty"
    mutableMap[50] = "Fifty"

    var entries = mutableMap.toList().map { "(${it.first}, ${it.second})"}
    println("\nusing toList() on mutable map")
    entries.forEach{print("$it ")}
}

Output:

using toList()
Keys list : [50, 20, 40, 10, 30]
Values list : [Fifty, Twenty, Fourty, Ten, Thirty]

using toList() on mutable map
(50, Fifty) (20, Twenty) (40, Fourty) (10, Ten) (30, Thirty) 

5. Kotlin Map to List using entries properties


map.entries properties will returns the key-value pairs. Use map() method  on the entries object.  We can use the any pattern in between the key and value.

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    var mutableMap: MutableMap<Int, String> = HashMap()

    mutableMap[10] = "Ten"
    mutableMap[20] = "Twenty"
    mutableMap[30] = "Thirty"
    mutableMap[40] = "Fourty"
    mutableMap[50] = "Fifty"

    var list : List<String> = mutableMap.entries.map { ("${it.key} -->  ${it.value}") }

    list.forEach{println(it)}
}

Output:

50 -->  Fifty
20 -->  Twenty
40 -->  Fourty
10 -->  Ten
30 -->  Thirty

6. Kotlin Map to List using keys and values


Use keys and values properties of map object to call map() method.

package com.javaprogramto.kotlin.collections.map.list

import java.util.HashMap

fun main(array: Array<String>) {

    var mutableMap: MutableMap<Int, String> = HashMap()

    mutableMap[10] = "Ten"
    mutableMap[20] = "Twenty"
    mutableMap[30] = "Thirty"
    mutableMap[40] = "Fourty"
    mutableMap[50] = "Fifty"

    var keysList : List<String> = mutableMap.keys.map { ("${it} ") }
    var valuesList : List<String> = mutableMap.values.map { ("${it} ") }

    println("---- keys list ------")
    keysList.forEach{println(it)}

    println("----- values list ------")
    valuesList.forEach{println(it)}
}

Output:

---- keys list ------
50 
20 
40 
10 
30 
----- values list ------
Fifty 
Twenty 
Fourty 
Ten 
Thirty 

7. Conclusion


in this article, We have seen how to convert Map to List in Kotlin programming and examples on different approaches.



Sunday, June 13, 2021

Java 8 IntStream With Working Examples

1. Overview

In this tutorial, We'll learn how to use the IntStream in java 8 and it uses with example programs.

For int primitives, the Java IntStream class is a specialization of the Stream interface. It's a stream of primitive int-valued items that can be used in both sequential and parallel aggregate operations.

AutoCloseable and BaseStream interfaces are implemented by IntStream, which is part of the java.util.stream package.

We will learn the following topics in this course.

  • IntStream Creation
  • ForEach loop
  • IntStream ranges
  • IntStream min and max
  • IntStream find
  • IntStrem map
  • IntStream filter
  • IntStream distinct
  • IntStream to Array
  • IntStream to List
Java 8 IntStream With Working Examples


2. Creating IntStream


An IntStream can be generated in a variety of ways, but it cannot be created using a new keyword.

The IntStream objects are created using the methods listed below.

  • IntStream.of()
  • IntStream.range()
  • IntStream.rangeclosed()
  • IntStream.generate()
  • IntStream.iterate()

Let us explore the ways to use these methods with example programs. to create an instance for IntStream with primitive int values.

2.1 IntStream.of()


This function returns a sequentially ordered stream with the provided values as its elements.

It is available in two forms: single element stream and multiple values stream.

IntStream of(int t) – Returns a stream consisting of a single supplied element.
IntStream of(int... values) – Returns a stream with all the components supplied.
package com.javaprogramto.java8.intstream;

import java.util.stream.IntStream;

public class IntStreamOf {

	public static void main(String[] args) {

		IntStream singleValue = IntStream.of(10);

		IntStream multipleValeus = IntStream.of(1, 5, 10, 20, 30);

	}

}
 

2.2 IntStream.range()


range() is used to generate the numbers in the order with incremental by one.

static IntStream range(int startInclusive, int endExclusive) -- here the end range is exclusive.

IntStream range10to30 = IntStream.range(10, 20);
 

2.3 IntStream.rangeclosed()


rangeClosed() is also used to generate the numbers in the order with incremental by one but it includes the end index of this method.

static IntStream rangeClosed(int startInclusive, int endInclusive)
IntStream range10to15closed = IntStream.range(10, 15);
 

2.4 IntStream.generate()


Use the generate() method if you wish to generate random numbers with custom logic.
IntStream random = IntStream.generate( () -> { return (int) Math.random() * 5000;});
 

2.5 IntStream.iterate()


The iterate() method is identical to the generate() method, except instead of random values, it uses incremental or decrement custom logic for large values.

Due to the fact that the iterate() method generates an infinite stream of integers, you must use the limit() function to get the first n numbers.
IntStream iterate = IntStream.iterate(1000, i -> i + 4000).limit(5);
 

3. IntStream forEach()


Typically we can use the traditional for loop for certain range. However, the same thing may be accomplished by using the IntStream.forEach() function instead.
package com.javaprogramto.java8.intstream;

import java.util.stream.IntStream;

public class IntStreamOf {

	public static void main(String[] args) {
		
		System.out.println("for loop");
		for(int i = 1000; i < 20000 ; i = i + 4000) {
			print(i);
		}
		
		System.out.println("intstream foreach loop");
		IntStream iterate = IntStream.iterate(1000, i -> i + 4000).limit(5);
		
		iterate.forEach(n -> print(n));
		
		
	}
	
	private static void print(int n) {
		System.out.println(n);
	}

}

 

4. IntStream ranges 


Two methods are offered by the IntStream API to work with numbers generated in a defined range.

range(start, endExclusive): excludes the end index from the output range.

rangeClosed(start, endInclusive): this method includes the end index from the output range.

The below program output gives you clear understanding between range() and rangeClosed() methods.
		IntStream range10to15range = IntStream.range(10, 15);
		IntStream range10to15closed = IntStream.rangeClosed(10, 15);
		
		System.out.println("range(10, 15) : "+Arrays.toString(range10to15range.toArray()));
		System.out.println("rangeClosed(10, 15) : "+Arrays.toString(range10to15closed.toArray()));
 
Output:
range(10, 15) : [10, 11, 12, 13, 14]
rangeClosed(10, 15) : [10, 11, 12, 13, 14, 15]
 

5. IntStream min and max


IntStream has utility methods for determining the minimum and maximum values from a series of numbers or random numbers.

Use min() method to retrieve the lowest value from int stream.
Use max() method to retrieve the highest value from int stream.
System.out.println("range(10, 15) min value : "+IntStream.range(10, 15).min().getAsInt());
System.out.println("range(10, 15) max value : "+IntStream.range(10, 15).max().getAsInt());
 
Output:
range(10, 15) min value : 10
range(10, 15) max value : 14
 

6. IntStream find value


Use findFirst() or findAny() methods on the InstStream object to get the first or any value.


By default, IntStream is created as sequential stream unless call the parallel() on the IntStream.

For sequential streams, the findFirst() and findAny() methods return the same result. If the stream is parallel, however, the findAny() method gives a random value.
System.out.println("findFirst value : "+IntStream.iterate(10, i -> i + 2).limit(100).findFirst().getAsInt());
System.out.println("findAny value : "+IntStream.iterate(10, i -> i + 2).limit(100).findAny().getAsInt());

System.out.println("parallel findAny value : "+IntStream.iterate(10, i -> i + 2).limit(100).parallel().findAny().getAsInt());
 
Output:
findFirst value : 10
findAny value : 10
parallel findAny value : 160
 

7. IntStream map() or flatMap()


We can transform the IntStream into the new form using map() method but flatMap() method does the flatten the IntStreams into primitives.

Usage of map() and flatMap() does not give much difference with IntStream usage.
IntStream mapInput = IntStream.iterate(10, i -> i + 1).limit(10);

System.out.println("map input stream : "+Arrays.toString(mapInput.toArray()));

IntStream mapOutput = mapInput.map( i -> i * 2);

System.out.println("map Output stream : "+Arrays.toString(mapOutput.toArray()));


IntStream input1 = IntStream.iterate(10, i -> i + 1).limit(10);

System.out.println("flat map : "+Arrays.toString(input1.flatMap( i -> IntStream.of(i)).toArray()));
 

Output:
map input stream : [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
map Output stream : [20, 22, 24, 26, 28, 30, 32, 34, 36, 38]
flat map : [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]

 

8. IntStream filter


Use filter() method to filter the integer values based on the given IntPredicate condition.

After applying the filter() method then next you can call forEach() or collect() method to convert it into List or Set.
IntStream stream = IntStream.range(100, 200);

// filter by number divisible by 5 and 7
System.out.println("numbers divisible by 5 and 7 are : ");
stream.filter(i -> (i % 5 == 0 && i % 7 == 0)).forEach(System.out::println);

IntStream stream2 = IntStream.range(100, 200);

List<Integer> primes = stream2.filter(IntStreamOf::checkPrime).boxed().collect(Collectors.toList());

System.out.println("Prime numbers (100, 200) are "+primes);
 
Output:
numbers divisible by 5 and 7 are : 
105
140
175
Prime numbers (100, 200) are [101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]

 

9. IntStream distinct()


Use distinct() method to remove the duplicate values from IntStream.
Arrays.toString(IntStream.of(1, 2, 3, 1, 2, 3).distinct().toArray());
 
Output:
[1, 2, 3]

 

10. IntStream to Array and List or Set


Use toArray() method to collect the output of IntStream into Array.
Use collect() method to collect the output of IntStream into List or Set.

To remove the duplicates from int stream, you can collect the results into Set rather than using distinct() method. But distinct() is recommended.
int[] intArray = IntStream.of(1, 2, 3, 1, 2, 3).toArray();
System.out.println("int array : "+Arrays.toString(intArray));


List<Integer> list = IntStream.of(1, 2, 3, 1, 2, 3).boxed().collect(Collectors.toList());
System.out.println("IntStream to List : "+list);

Set<Integer> set = IntStream.of(1, 2, 3, 1, 2, 3).boxed().collect(Collectors.toSet());
System.out.println("IntStream to Set : "+set);

 

11. Conclusion


In this article, we have seen all useful methods of IntStream with the useful examples.



How to compare two ArrayList for equality in Java 8? ArrayList equals() or containsAll() methods works?

1. Introduction


In this article, We'll learn how to compare two ArrayLists for checking Objects equality.


ArrayList has an equal() method that takes one argument type of Object. This equals() method compares the passed list object with the current list object. If both lists are having same values then it returns true, otherwise false. equals()

Read more on how to compare two strings lexicographically.

Example programs are shown on equals(), containsAll() and java 8 Stream API.

At the end of the article you will be good with comparing two lists and find differences between two lists in java


How to compare two ArrayList for equality in Java 8? ArrayList equals() or containsAll() methods works?