Categories
collections java

join two arraylist in java with example

In this post, we will learn to join two arraylist in java with example

ArrayList is a dynamic array concept in java. We use ArrayList in so many places.

Syntax
list1.addAll(list2);

From the above syntax list2 will added to list1.

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

public class Join2List {

	public static void main(String[] args) {
		try {
			List<String> list1 = new ArrayList<String>();
			List<String> list2 = new ArrayList<String>();

			list1.add("Rajesh");
			list1.add("Usha");

			list2.add("Kumar");
			list2.add("Nandhini");

			System.out.println("---List1 value before adding list2---");
			for (String string : list1) {
				System.out.println(string);
			}

			// Adding list2 to list1
			list1.addAll(list2);

			System.out.println("---List1 value After adding list2---");

			for (String string : list1) {
				System.out.println(string);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
Output
---List1 value before adding list2---
Rajesh
Usha
---List1 value After adding list2---
Rajesh
Usha
Kumar
Nandhini
Github

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

Related Articles

ArrayList in java with example

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
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

sorting operations in java using streams

In this example, we learn sorting operations in java using streams

In Java 8 it is easy to sort records from an arraylist

Streams API providing powerful features to sort the records from a list without modifying it

This will returns a stream consisting of the sorted elements

Syntax

Stream sorted()
list.stream().sorted({operations});

Ascending Example

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

public class AscendingSortingStreams {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Ball");
        list.add("Apple");
        list.add("Cat"); // printitng values before sorting
        System.out.println("Values before sorting ");
        list.stream().forEach(x -> System.out.println(x));
        System.out.println("*** Values After sorting ***");
        list.stream().sorted().forEach(x -> System.out.println(x));
    }
}

Output

Values before sorting 
Ball
Apple
Cat
*** Values After  sorting ***
Apple
Ball
Cat

Descending Example

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

public class DescendingSortingStreams {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Ball");
        list.add("Apple");
        list.add("Cat");
        // printitng values before sorting
        System.out.println("Values before sorting ");
        list.stream().forEach(x -> System.out.println(x));
        System.out.println("*** Values After sorting ***");
        // Comparator.reverseOrder() will sort the records in descending order
        list.stream().sorted(Comparator.reverseOrder()).forEach(x -> System.out.println(x));
    }
}

Output

Values before sorting 
Ball
Apple
Cat
*** Values After  sorting ***
Cat
Ball
Apple

References

Oracle Docs

Related Articles

filter operations in streams on java 

Iterate list using streams in 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

Check key exists in Hashmap Java

Check key exists in Hashmap Java

In below example we are going to Check key exists in Hashmap java

Syntax

<span class="token function">containsKey</span><span class="token punctuation">(</span><span class="token punctuation">)</span>

Example

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

public class KeyExistsHashMapExample {

  public static void main(String[] args) {
    Map<String, String> hashMap = new HashMap<String, String>();
    hashMap.put("1", "Car");
    hashMap.put("2", "Bus");
    hashMap.put("3", "Train");
    boolean isKeyAvaillable = hashMap.containsKey("1");
    if(isKeyAvaillable) {
      System.out.println("The value is "+hashMap.get("1"));
    }
    else {
      System.out.println("Key is not availlable");
    }
  }
}

Output

The value is Car

Reference

https://beginnersbug.com/hashmap-in-java/
https://docs.oracle.com/javase/8/docs/api/java/util/Map.html#containsKey-java.lang.Object-

Download

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

Categories
collections java

Sort an Arraylist in java with example

In this tutorial, we will learn how to Sort an Arraylist in java with example by ascending order using collections class

If you are new to array list refer below link to understand array list
https://beginnersbug.com/arraylist-in-java/

Features

  • Sort the specified list into ascending order,
  • This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
  • The specified list must be modifiable, but need not be resizable.

Syntax

Collections.sort(list);

Example

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

public class SortArrayListExample {
    public static void main(String[] args) {
        List<String> list = new ArrayList();
        list.add("Car");
        list.add("Zebra");
        list.add("Apple");
        list.add("Ball");
        System.out.println("Array list values before sorting \n");
        for (String string : list) {
            System.out.println("Value is " + string);
        }
        // Below sort method will sort your list
        Collections.sort(list);
        System.out.println("\nArray list values after sorting \n");
        for (String string : list) {
            System.out.println("Value is " + string);
        }
    }
}

Output

Array list values before sorting 

Value is Car
Value is Zebra
Value is Apple
Value is Ball

Array list values after sorting 

Value is Apple
Value is Ball
Value is Car
Value is Zebra

Reference

https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html

Related Articles

iterate stream with index in Java8

foreach in java8 using streams