Categories
collections java

convert iterator to list in java

In this tutorial, we will learn convert iterator to list in java

Here we are giving two approach to convert iterator to list in java

Syntax in Java 8
ArrayList<String> list = new ArrayList<String>();
iterator.forEachRemaining(list::add);
Syntax in Java 7
ArrayList<String> list = new ArrayList<String>();
while (iterator.hasNext()) {
  String string = (String) iterator.next();
  list.add(string);
}
Example
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;

public class IteratorToList {

	public static void main(String[] args) {

		Iterator<String> iterator = Arrays.asList("Rajesh", "Kumar", "Beginners", "Bug").iterator();
		convertToListJava7(iterator);
		convertToListJava8(iterator);

	}

	/**
	 * Java 7 Approach
	 * 
	 * @param iterator
	 * @return
	 */
	public static ArrayList<String> convertToListJava7(Iterator<String> iterator) {
		ArrayList<String> list = new ArrayList<String>();
		while (iterator.hasNext()) {
			String string = (String) iterator.next();
			list.add(string);
		}

		return list;
	}

	/**
	 * Java 8 Apporach
	 * 
	 * @param iterator
	 * @return
	 */
	public static ArrayList<String> convertToListJava8(Iterator<String> iterator) {
		ArrayList<String> list = new ArrayList<String>();
		iterator.forEachRemaining(list::add);
		return list;
	}

}
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/list/IteratorToList.java

Related Articles

Iterate list using streams in java

Categories
microservices spring-boot

how to create spring boot application

In this tutorial, we will learn how to create spring boot application

What is Spring boot

Spring Boot makes it easy to create stand-alone, production-grade application. It internally use Spring framework and have embedded tomcat servers, nor need to deploy war in any servers

Also easy to create,configure&run

What You Will learn

End of this tutorial, you will learn to create a spring boot application

Annotation
@SpringBootApplication
Dependency
<parent>                                                              
  <groupId>org.springframework.boot</groupId>                         
  <artifactId>spring-boot-starter-parent</artifactId>                 
  <version>2.2.6.RELEASE</version>                                    
  <relativePath /> <!-- lookup parent from repository -->             
</parent>

Time needed: 30 minutes

Steps

  1. Navigate to Spring initializr website

    Click on this url https://start.spring.io/register spring boot micro-services to eureka discovery server

  2. Choose project as Maven

    In this tutorial I am using Maven. You can use gradle or groovy also

  3. Choose language as Java

    Here I am using Java. But we have option for Kotlin & Groovy also

  4. Spring Boot Version

    Please select the stable version, I am using 2.2.6

  5. Enter Group,artifact,Name & description

    Enter the groupid,artifactid&name as you wanted

  6. Packaging as Jar

    Choose Jar, But you have option for war also

  7. Java Verison

    Here I am using java 8

  8. Add Spring Web as dependency

    In case you going you want to expose rest service, Click on the add dependency and select spring web.

  9. Click on the Genreate

    Once you filled all these details click on the Generate Button.
    It will download .rar format

  10. Extract the downloaded file

    Once your download complete, Extract the downloaded .rar file

  11. Import in Eclipse

    After Extracting, Import the project in eclipse

  12. Navigate to Main Class

    Navigate to Main class which will be under src/main/java
    and Make sure the class have @SpringBootApplication annotation

  13. Run

    Right click the class and choose the Run As –> Java Application

  14. Verify logs

    Once your application starts you can see below logs in console

Tomcat started on port(s): 8080 (http) with context path ''
Updating port to 8080
Started StudentApplication in 22.834 seconds (JVM running for 24.503)
Related Articles

create netflix eureka discovery server using spring boot

register spring boot micro-services to eureka discovery

Categories
java

Base64 Encoding using Java

In Below example we will learn how to use Base64 Encoding using Java

Finally Java8 incorporated Base64 Encoding. Base64 is one of the common Encoding mechanism.

Syntax
Base64.getEncoder().encodeToString(textForEncoding.getBytes());
Example

import java.util.Base64;

public class Base64Encodng {

	public static void main(String[] args) {
		try {
			String textForEncoding = "QWERTY TEXT";
			String encodedString = Base64.getEncoder().encodeToString(textForEncoding.getBytes());
			System.out.println(encodedString);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
UVdFUlRZIFRFWFQ=

The length of output encoded String must be a multiple of 3. else the output will be padded with additional pad characters (`=`).
But we have option to encode without padding also

Syntax
Base64.getEncoder().withoutPadding().encodeToString(textForEncoding.getBytes());
Example without Padding

import java.util.Base64;

public class Base64Encodng {

	public static void main(String[] args) {
		try {
			String textForEncoding = "QWERTY TEXT";
			String encodedString = Base64.getEncoder().withoutPadding().encodeToString(textForEncoding.getBytes());
			System.out.println(encodedString);		

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
UVdFUlRZIFRFWFQ
Decoding Syntax
Base64.getDecoder().decode(encodedString.getBytes());
Example

import java.util.Base64;

public class Base64Encodng {

	public static void main(String[] args) {
		try {
			String textForEncoding = "QWERTY TEXT";
			String encodedString = Base64.getEncoder().withoutPadding().encodeToString(textForEncoding.getBytes());
			System.out.println(encodedString);
			
			byte[] decodeByte = Base64.getDecoder().decode(encodedString.getBytes());
			String decodedValue=new String(decodeByte);
			System.out.println(decodedValue);

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
UVdFUlRZIFRFWFQ
QWERTY TEXT
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/Base64Encodng.java

Categories
collections java

get key and value from hashmap in java

In this tutorial, we will learn about get key and value from hashmap in java

Example Using Java 8

import java.util.HashMap;
import java.util.Map;

public class KeyValueFromHashMap {

	public static void main(String[] args) {
		try {
			Map<String, String> hashMap = new HashMap();
			hashMap.put("1", "Car");
			hashMap.put("2", "Bus");
			hashMap.put("3", "Train");

			// Below code only work above java 8
			hashMap.forEach((key, value) -> {
				System.out.println("Value of " + key + " is " + value);
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
Value of 1 is Car
Value of 2 is Bus
Value of 3 is Train
Example using java 7

import java.util.HashMap;
import java.util.Map;

public class KeyValueFromHashMap {

	public static void main(String[] args) {
		try {
			Map<String, String> hashMap = new HashMap();
			hashMap.put("1", "Car");
			hashMap.put("2", "Bus");
			hashMap.put("3", "Train");

			for (Map.Entry<String, String> entry : hashMap.entrySet()) {
				System.out.println(entry.getKey() + " Value is " + entry.getValue());
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
Output
1 Value is Car
2 Value is Bus
3 Value is Train
GitHub Url

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/KeyValueFromHashMap.java

Related Articles

Check key exists in Hashmap Java

Categories
collections java

iterate stream with index in Java8

In this post, we will learn to iterate stream with index in Java8

We will come across multiple streams tutorials, but in all the tutorials we never iterate with index numbers

In order to find the current index or other numeric operations index number will help us to get the position

In this tutorial, we are going to use IntStream  to get  index of the arraylist

Because there is no straight way to get index number in streams

Syntax
IntStream.range(start, end)
Example

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

public class IterateStreamWithIndex {

	public static void main(String[] args) {
		try {
			List<String> list = new ArrayList<String>();
			list.add("India");
			list.add("USA");
			list.add("Germany");

			IntStream.range(0, list.size())
					.forEach(x -> System.out.println("The index is " + x + " Value is " + list.get(x)));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Output
The index is 0 Value is India
The index is 1 Value is USA
The index is 2 Value is Germany
Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/IterateStreamWithIndex.java

Related Articles

foreach in java8 using streams

sorting operations in java using streams

Categories
collections java

foreach in java8 using streams

In this tutorial, we will learn about foreach in java8 using streams

In java8, We can easily iterate a list using streams.

Streams API provided a lot of features. In this post, we are going to see about foreach

Syntax
stream().forEach({operations});
Example

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

public class ForEachExample {

	public static void main(String[] args) {
		try {

			List studentList = new ArrayList();
			Student student = null;

			student = new Student();
			student.setId(1);
			student.setName("Rajesh");
			student.setAddress("Mumbai");
			studentList.add(student);

			student = new Student();
			student.setId(1);
			student.setName("Kumar");
			student.setAddress("Chennai");
			studentList.add(student);

			studentList.stream()
					.forEach(x -> System.out.println("Name is " + x.getName() + " Address is " + x.getAddress()));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
Student.java

public class Student {

	private int id;
	private String name;
	private String address;

	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 String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}
Output
Name is Rajesh Address is Mumbai
Name is Kumar Address is Chennai
Related Article

sorting operations in java using streams

Iterate list using streams in java

Github

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/ForEachExampleUsingStreams.java

Categories
collections java

filter operations in streams on java 

In this example we learn filter operations in streams on java 

In Java 8 it is easy to filter record from an arraylist

Streams API providing powerful features to filter an record from a list without modifying it

This will returns a stream consisting of the elements of this stream that match the given predicate.

Syntax
Stream filter(Predicate<? super T> predicate)<br><br>
list.stream().filter({operations});
Example
import java.util.ArrayList;
import java.util.List;

public class FilterExample {

	public static void main(String[] args) {

		List studentList = new ArrayList();
		Student student = null;

		student = new Student();
		student.setId(1);
		student.setName("Rajesh");
		student.setAddress("Mumbai");
		studentList.add(student);

		student = new Student();
		student.setId(1);
		student.setName("Kumar");
		student.setAddress("Chennai");
		studentList.add(student);

		studentList.stream().filter(x -> x.getName().equals("Rajesh"))
		.forEach(x -> System.out.print(x.getAddress()));

	}

}
Person.java
public class Student {

	private int id;
	private String name;
	private String address;

	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 String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}
Output
Mumbai
Reference

oracle docs

Related Articles

Iterate list using streams in java

iterate stream with index in Java8

Categories
collections java

Iterate list using streams in java

In this example, we will learn about iterate list using streams in java with example
It was introduced on Java 8

Features of Streams
  • No Storage
  • we can do arithmetic operations
  • we can filter the data without removing.
Syntax
list.stream().forEach((x) -> {operations});
Example
import java.util.ArrayList;
import java.util.List;

public class IterateListUsingStreams {

    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Apple");
        list.add("Pineapple");
        list.add("Papaya");
        list.stream().forEach((x) -> System.out.println(x));
    }

}
Output
Apple
Pineapple
Papaya
Example with Pojo
Student.java
public class Student {

	private int id;
	private String name;
	private String address;

	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 String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

}
IterateListUsingStreams2 .java
import java.util.ArrayList;
import java.util.List;

public class IterateListUsingStreams2 {

	public static void main(String[] args) {

		List studentList = new ArrayList();
		Student student = null;

		student = new Student();
		student.setId(1);
		student.setName("Rajesh");
		student.setAddress("Chennai");
		studentList.add(student);

		student = new Student();
		student.setId(1);
		student.setName("Kumar");
		student.setAddress("Chennai");
		studentList.add(student);

		studentList.stream().forEach((x) -> System.out.println("Student Id is "+x.getId()+" Name is "+x.getName()));

	}

}
Output
Student Id is 1 Name is Rajesh
Student Id is 1 Name is Kumar
References

https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

GitHub

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/IterateListUsingStreams.java

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/IterateListUsingStreams2.java

Related Articles

iterate stream with index in Java8

ArrayList in java with example

Categories
collections java

HashMap in java with example

HashMap in java with example

In this tutorial we will learn about HashMap in java with example

Hashmap is used store key and value pair in java which implemented map interface internally

Features

  • It will not allow duplicate keys
  • We can store null value as a key
  • It is not thread safe

Example


import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class HashmapExample {
	public static void main(String[] args) {
		try {
			Map<String, String> hashMap = new HashMap();
			hashMap.put("1", "Car");
			hashMap.put("2", "Bus");
			hashMap.put("3", "Train");

			for (Map.Entry<String, String> entry : hashMap.entrySet()) {
				System.out.println(entry.getKey() + " Value is " + entry.getValue());
			}
			System.out.println("---------------");
			// Below code only work above java 8
			hashMap.forEach((key, value) -> {
				System.out.println("Value of " + key + " is " + value);
			});

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

Output

1 Value is Car
2 Value is Bus
3 Value is Train
---------------
Value of 1 is Car
Value of 2 is Bus
Value of 3 is Train

Reference

https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html
https://beginnersbug.com/check-key-exists-in-hashmap-java/

Download

https://github.com/rkumar9090/BeginnersBug/blob/master/BegineersBug/src/com/geeks/example/HashmapExample.java