Wednesday, January 12, 2022

Java Stream - Convert Stream to Set

In this tutorial you’ll see how to convert a Java Stream to Set using collector method and Collectors.toSet(), Collectors.toUnmodifiableSet() and Collectors.toCollection() methods.

1. In this example a Stream of strings is converted to a Set of strings. For that you can use Collectors.toSet() method which can be passed to the collect method.

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

public class StreamToSet {

  public static void main(String[] args) {
    // Creating stream
    Stream<String> cityStream = Stream.of("Chicago", "Mumbai", 
            "New Delhi", "Paris");
    // Converting Stream to Set
    Set<String> citySet = cityStream.collect(Collectors.toSet());
    // Checking the type of the created Set
    System.out.println(citySet.getClass().getName());
    System.out.println("Set Elements- " + citySet);

  }
}

Output

java.util.HashSet
Set Elements- [New Delhi, Chicago, Mumbai, Paris]

Though the Javadocs say “There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned” but usually HashSet is returned as checked in the example by printing type of the Set.

2. If you want any other type of Set for example LinkedHashSet while converting Stream to Set then you can use Collectors.toCollection(Supplier<C> collectionFactory) method and explicitly specify the type of collection where stream elements are to be stored.

public class StreamToSet {

  public static void main(String[] args) {
    // Creating stream
    Stream<String> cityStream = Stream.of("Chicago", "Mumbai", 
            "New Delhi", "Paris");
    // Converting Stream to Set
    Set<String> citySet = cityStream.collect(Collectors.toCollection(LinkedHashSet :: new));
    // Checking the type of the created Set
    System.out.println(citySet.getClass().getName());
    System.out.println("Set Elements- " + citySet);
  }
}

Output

java.util.LinkedHashSet
Set Elements- [Chicago, Mumbai, New Delhi, Paris]

As evident from the output now the element ordering is maintained because elements are stored in a LinkedHashSet.

3. If you want to ensure that the returned Set is unmodifiable then you can use Collectors.toUnmodifiableSet() method.

public class StreamToSet {

  public static void main(String[] args) {
    Stream<String> cityStream = Stream.of("Chicago", "Mumbai", 
            "New Delhi", "Paris");
    Set<String> citySet = cityStream.collect(Collectors.toUnmodifiableSet());
    System.out.println("Set Elements- " + citySet);
  }
}
Any attempt to modify the returned Set results in error.
Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
	at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.add(ImmutableCollections.java:147)

4. In this example we’ll see how to get a sub-set from a List of objects by using the original List as stream source and using Collectors.toSet() method to collect required elements in a Set.

Employee class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
    return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}

If you want to get a Set of employees having salary greater than 10000 then you can use filter() method along with collector() to collect the filtered elements to the Set.

public class StreamToSet {

  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                 new Employee("E002", 35, "Shelly", 'F', 7000), 
                 new Employee("E003", 24, "Mark", 'M', 9000), 
                 new Employee("E004", 37, "Ritu", 'F', 11000),
                 new Employee("E005", 32, "Anuj", 'M', 12000), 
         new Employee("E006", 28, "Amy", 'F', 14000)); 
     
    Set<Employee> tempSet = empList.stream()
                     .filter(e -> e.getSalary() > 10000)
                     .collect(Collectors.toSet());
    System.out.println("Set Elements- " + tempSet);
  }
}

Output

Set Elements- [Emp Id: E005 Name: Anuj Age: 32, Emp Id: E004 Name: Ritu Age: 37, Emp Id: E006 Name: Amy Age: 28]

4. In this example we’ll try to get the name of male employees in a Set. That will mean using map() also along with filter() and collect() methods.

public class StreamToSet {

  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                 new Employee("E002", 35, "Shelly", 'F', 7000), 
                 new Employee("E003", 24, "Mark", 'M', 9000), 
                 new Employee("E004", 37, "Ritu", 'F', 11000),
                 new Employee("E005", 32, "Anuj", 'M', 12000), 
         new Employee("E006", 28, "Amy", 'F', 14000)); 
     
    Set<String> tempSet = empList.stream()
                     .filter(e -> e.getGender() == 'M')
                     .map(Employee::getName)
                     .collect(Collectors.toSet());
    System.out.println("Set Elements- " + tempSet);
  }
}

Output

Set Elements- [Mark, Anuj, Ram]

That's all for this topic Java Stream - Convert Stream to Set. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - Convert Stream to List
  2. Java Stream - concat() With Examples
  3. Java Stream API Examples
  4. Java Stream - sorted() With Examples

You may also like-

  1. AutoBoxing And UnBoxing in Java
  2. Heap Memory Allocation in Java
  3. Difference Between equals() Method And equality Operator == in Java
  4. Why no Multiple Inheritance in Java
  5. Creating Tar File And GZipping Multiple Files in Java
  6. Interface in Python
  7. Spring Transaction Attributes - Propagation And Isolation Level Settings
  8. Java Program to Write File in HDFS

Monday, January 10, 2022

Java Stream - Convert Stream to List

In this tutorial you’ll see how to convert a Java Stream to List using collect method and Collectors.toList() and Collectors.toCollection() utility methods.

1. In this example a Stream of strings is converted to a List of strings.

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

public class StreamToList {

  public static void main(String[] args) {
    // Creating stream
    Stream<String> cityStream = Stream.of("Chicago", "Mumbai", 
            "New Delhi", "Paris");
    // Converting Stream to List
    List<String> cityList = cityStream.collect(Collectors.toList());
    // Checking the type of the created List
      System.out.println(cityList.getClass().getName());
      System.out.println("List Elements- " + cityList);
  }
}

Output

java.util.ArrayList
List Elements- [Chicago, Mumbai, New Delhi, Paris]

Though the Javadocs say “There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned” but usually ArrayList is returned as checked in the example by printing type of the List.

2. If you want any other type of List i.e. LinkedList while converting Stream to List then you can use Collectors.toCollection(Supplier<C> collectionFactory) method and explicitly specify the type of collection where stream elements are to be stored.

public class StreamToList {

  public static void main(String[] args) {
    // Creating stream
    Stream<String> cityStream = Stream.of("Chicago", "Mumbai", 
            "New Delhi", "Paris");
    // Converting Stream to List
    List<String> cityList = cityStream.collect(Collectors.toCollection(LinkedList :: new));
    // Checking the type of the created List
      System.out.println(cityList.getClass().getName());
      System.out.println("List Elements- " + cityList);
  }
}

Output

java.util.LinkedList
List Elements- [Chicago, Mumbai, New Delhi, Paris]

3. In this example we’ll see how to get a sub-list from a list of objects by using the original list as stream source and using Collectors class toList() method to collect required elements in another list.

Employee class

public class Employee {
	private String empId;
	private int age;
	private String name;
	private char gender;
	private int salary;
	Employee(String empId, int age, String name, char gender, int salary){
        this.empId = empId;
        this.age = age;
        this.name = name;
        this.gender = gender;
        this.salary = salary;
    }
	public String getEmpId() {
		return empId;
	}

	public int getAge() {
		return age;
	}

	public String getName() {
		return name;
	}

	public char getGender() {
		return gender;
	}

	public int getSalary() {
		return salary;
	}
	@Override
	public String toString() {
	    return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
	}
}

If you want to get a List of employees having salary greater than 10000 then you can use filter() method along with collector() to collect the filtered elements to the list.

public class StreamToList {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                 new Employee("E002", 35, "Shelly", 'F', 7000), 
                 new Employee("E003", 24, "Mark", 'M', 9000), 
                 new Employee("E004", 37, "Ritu", 'F', 11000),
                 new Employee("E005", 32, "Anuj", 'M', 12000), 
         new Employee("E006", 28, "Amy", 'F', 14000)); 
     
     List<Employee> tempList = empList.stream()
                     .filter(e -> e.getSalary() > 10000)
                     .collect(Collectors.toList());
      System.out.println("List Elements- " + tempList);
  }
}

Output

List Elements- [Emp Id: E004 Name: Ritu Age: 37, Emp Id: E005 Name: Anuj Age: 32, Emp Id: E006 Name: Amy Age: 28]

4. In this example we’ll try to get the name of female employees in a separate list. That will mean using map() also along with filter() and collect() methods.

public class StreamToList {

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                 new Employee("E002", 35, "Shelly", 'F', 7000), 
                 new Employee("E003", 24, "Mark", 'M', 9000), 
                 new Employee("E004", 37, "Ritu", 'F', 11000),
                 new Employee("E005", 32, "Anuj", 'M', 12000), 
         new Employee("E006", 28, "Amy", 'F', 14000)); 
     
     List<String> tempList = empList.stream()
                     .filter(e -> e.getGender() == 'F')
                     .map(e -> e.getName())
                     .collect(Collectors.toList());
      System.out.println("List Elements- " + tempList);
  }
}

Output

List Elements- [Shelly, Ritu, Amy]

That's all for this topic Java Stream - Convert Stream to List. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - boxed() With Examples
  2. Java Stream - concat() With Examples
  3. Spliterator in Java
  4. Java Stream - Collectors.groupingBy() With Examples

You may also like-

  1. Buffered Streams in Java IO
  2. JShell in Java With Examples
  3. JVM Run-Time Data Areas - Java Memory Allocation
  4. Java Nested Class And Inner Class
  5. Matrix Subtraction Java Program
  6. Java Lambda Expressions Interview Questions And Answers
  7. Installing Docker on Windows
  8. Angular @HostListener Decorator With Examples

Friday, January 7, 2022

Arithmetic And Unary Operators in Java

For basic mathematical operation the Java programming language provides arithmetic operators like addition (+), subtraction (-), division (/), multiplication(*) and modulus (%, which divides one operand by another and returns the remainder as its result).

In this post we'll see what all arithmetic operators are available in Java. Apart from that we'll also learn about Compound assignment operators, Unary operators and Increment and decrement operators in Java.


Arithmetic operators in Java

Operator Description
+Additive operator (also used for String concatenation)
-Subtraction operator
*Multiplication operator
/Division operator
%Remainder operator

Java arithmetic operators example

public class ArithmeticDemo {

 public static void main(String[] args) {
  int num1 = 3;
  int num2 = 4;
  int result = num1 + num2;
  System.out.println("Addition result - " + result);
  // Subtraction
  result = result - 3;
  System.out.println("Subtraction result - " + result);
  // Division
  result = result/2;
  System.out.println("Division result - " + result);
  // Multiplication
  result = result * 6;
  System.out.println("Multiplication result - " + result);
  // Modulo division
  result = result % 8;
  System.out.println("Modulo division result - " + result);
  
  // overloaded + operator for string concatenation
  String str1 = "This is ";
  String str2 = "a string";
  String concatString = str1 + str2;
  System.out.println("Concatenated String " + concatString);
 }
}

Output

Addition result - 7
Subtraction result - 4
Division result - 2
Multiplication result - 12
Modulo division result - 4
Concatenated String This is a string

Compound assignment operators in Java

You can also combine the arithmetic operator with the assignment operator to create compound assignments. For example x = x + 7; can also be written as x += 7;

Operator Description
+=Addition assignment
–=Subtraction assignment
*=Multiplication assignment
/=Division assignment
%=Modulus assignment

Java Compound assignment operators example

public class OperatorDemo {

 public static void main(String[] args) {
  int x = 5;
  int y = 6;
  int z = 7;
  int p = 4;
  int q = 16;
  
  x += 4;
  System.out.println("x - " + x);
  
  y -= 2;
  System.out.println("y - " + y);
  
  z *= 3;
  System.out.println("z - " + z);
  
  p /= 2;
  System.out.println("p - " + p);
  
  q %= 3;
  System.out.println("q - " + q);

 }
}

Output

x - 9
y - 4
z - 21
p - 2
q – 1

Unary operators in Java

Operator Description
+Unary plus operator; indicates positive value (numbers are positive by default though)
-Unary minus operator; negates an expression
++Increment operator; increments a value by 1
--Decrement operator; decrements a value by 1
!Logical complement operator; inverts the value of a boolean

Java Unary operators example

Let’s see an example where unary plus operator, unary minus operator and logical component operator are used.

public class OperatorDemo {

 public static void main(String[] args) {
  // unary plus operator
  int x = +5;
  System.out.println("x = " + x);
  
  // unary minus operator
  x = -x;
  System.out.println("x = " + x);
  
  boolean flag = false;
  System.out.println("flag = " + flag);
  // logical component operator
  System.out.println("flag = " + !flag);

 }
}

Output

x = 5
x = -5
flag = false
flag = true

Increment and decrement operators in Java

The increment operator increases its operand value by 1. For example x = x + 1; can be written as x++; using increment operator.

Same way decrement operator decreases its operand value by 1. For example x = x – 1; can be written as x--; using decrement operator.

The increment/decrement operators can be applied before (prefix) or after (postfix) the operand. For example prefix code ++x; or the postfix code x++; both will result in x incremented by one.

Difference between prefix and postfix is that in prefix version operand is incremented/decremented and that value is used in the expression. Whereas in postfix version original value is used in the expression and then the operand is incremented/decremented.

As example-

x = 7;
y = ++x;

Here y has the value 8 because the operand is incremented before using it in expression.

X = 7;
y = x++;

Here y has the value 7 because the original value is used in the expression and then the operand is incremented. So x is 8 but y has the original value of x which was 7.

Java Increment and decrement operators example

public class OperatorDemo {

 public static void main(String[] args) {
  // prefix
  int x = 5;
  int y = ++x;
  System.out.println("x - " + x);
  System.out.println("y - " + y);
  
  // postfix
  int a = 8;
  int b = a++;
  System.out.println("a - " + a);
  System.out.println("b - " + b);
  
  y = --x;
  System.out.println("x - " + x);
  System.out.println("y - " + y);
  
  b = a--;
  System.out.println("a - " + a);
  System.out.println("b - " + b);
  
 }
}

Output

x - 6
y - 6
a - 9
b - 8
x - 5
y - 5
a - 8
b - 9

That's all for this topic Arithmetic And Unary Operators in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Conditional Operators in Java With Examples
  2. Ternary Operator in Java With Examples
  3. instanceof Operator in Java With Examples
  4. BigDecimal in Java With Examples
  5. Switch-Case Statement in Java With Examples

You may also like-

  1. Association, Aggregation and Composition in Java
  2. Initializer block in Java
  3. Array in Java
  4. Nested class and Inner class in Java
  5. Serialization and Deserialization in Java
  6. Race Condition in Java Multi-Threading
  7. How HashSet Works Internally in Java
  8. Spring Bean Life Cycle

Thursday, January 6, 2022

Java Stream - concat() With Examples

concat() method in Java Stream API takes two streams as arguments and returns a concatenated stream whose elements are all the elements of the first stream followed by all the elements of the second stream.

Syntax of concat() method

concat(Stream<? extends T> a, Stream<? extends T> b)

Here parameters are-

  • a - the first stream
  • b - the second stream

Method returns a merged stream

The resulting stream is ordered if both of the input streams are ordered, and parallel if either of the input streams is parallel.

concat() method Java examples

1. Using concat() method to merge two streams of integers.

import java.util.stream.Stream;

public class StreamConcat {

  public static void main(String[] args) {
    Stream<Integer> stream1 = Stream.of(1, 2, 3);
      Stream<Integer> stream2 = Stream.of(4, 5, 6);
      Stream<Integer> mergedStream = Stream.concat(stream1, stream2);
      mergedStream.forEach(System.out::println);
  }
}

Output

1
2
3
4
5
6

2. Merging two Collections (Lists) by using concat() method of Java Stream API.

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

public class StreamConcat {

  public static void main(String[] args) {
    List<String> strList1 = Arrays.asList("A","B","C","D");
    List<String> strList2 = Arrays.asList("E","F","G","H");
    // Getting streams using Lists as source
    Stream<String> stream1 = strList1.stream();
    Stream<String> stream2 = strList2.stream();
    
      Stream<String> mergedStream = Stream.concat(stream1, stream2);
      mergedStream.forEach(System.out::println);
  }
}

Output

A
B
C
D
E
F
G
H

3. You can also use concat() method along with other methods of the Java Stream, for example you can write a program to merge 2 lists while removing duplicates which can be done by using distinct() method.

public class StreamConcat {

  public static void main(String[] args) {
    List<String> strList1 = Arrays.asList("A","B","C","D");
    List<String> strList2 = Arrays.asList("E","B","G","A");
    // Getting streams using Lists as source
    Stream<String> stream1 = strList1.stream();
    Stream<String> stream2 = strList2.stream();
    
      Stream<String> mergedStream = Stream.concat(stream1, stream2).distinct();
      mergedStream.forEach(System.out::println);
  }
}

Output

A
B
C
D
E
G

4. Using concat() to merge multiple streams. You can also merge more than two streams by nesting the concat method.

public class StreamConcat {

  public static void main(String[] args) {
      Stream<Integer> stream1 = Stream.of(1, 2);
      Stream<Integer> stream2 = Stream.of(3, 4, 5);
      Stream<Integer> stream3 = Stream.of(7, 8, 9);
      Stream<Integer> stream4 = Stream.of(10, 11);
      Stream<Integer> mergedStream = Stream.concat(stream1, 
              Stream.concat(Stream.concat(stream2, stream3), stream4));
      mergedStream.forEach(e -> System.out.print(e + " "));
  }
}

Output

1 2 3 4 5 7 8 9 10 11 

That's all for this topic Java Stream - concat() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - count() With Examples
  2. Java Stream - boxed() With Examples
  3. Java Stream - findFirst() With Examples
  4. Java Stream - sorted() With Examples
  5. Java Stream - skip() With Examples

You may also like-

  1. Reflection in Java - Getting Class Information
  2. Java do-while Loop With Examples
  3. strictfp in Java
  4. Count Number of Times Each Character Appears in a String Java Program
  5. Stack Implementation in Java Using Linked List
  6. Class And Object in Python
  7. Spring WebFlux Example Using Functional Programming - Spring Web Reactive
  8. Highlight Currently Selected Menu Item Angular Routing Example

Wednesday, January 5, 2022

Find Duplicate Characters in a String With Repetition Count Java Program

In this post we’ll see a Java program to find duplicate characters in a String along with repetition count of the duplicates.

Finding duplicates characters in a String and the repetition count program is easy to write using a HashMap but you may be asked to write it without using any Java collection. Java 8 onward, you can also write this logic using Java Stream API. In this post we’ll see all of these solutions.


Java program to find duplicate characters in a String wihout using any library

If you are not using HashMap then you can iterate the passed String in an outer and inner loop and check if the characters are equal or not. If equal, then increment the count. In case characters are equal you also need to remove that character from the String so that it is not counted again in further iterations.

public class DuplicateChars {

  public static void main(String[] args) {   
    findDuplicateCharsWithCount("kakatua parrot is a bird");
    System.out.println("------------");
    findDuplicateCharsWithCount("John was jealous");
    System.out.println("------------");
    findDuplicateCharsWithCount("rats");
  }
    
  private static void findDuplicateCharsWithCount(String str) {
    System.out.println("Duplicates in- "+ str);
    int count;
    for(int i = 0; i < str.length(); i++) {
      count = 1;
      //Take one char at a time
      char c = str.charAt(i);
      // don't count the spaces
      if(c == ' ') 
        continue;
      for(int j = i + 1; j < str.length(); j++) {
        if(c == str.charAt(j)) {
          count++;
          // remove the char so that it is not picked again
          // in another iteration
          str = str.substring(0, j) + str.substring(j+ 1);
        }
      }
      if(count > 1) {
        System.out.println(c + " found " + count + " times");
      }
    }
  }
}

Output

Duplicates in- kakatua parrot is a bird
k found 2 times
a found 5 times
t found 2 times
r found 3 times
i found 2 times
------------
Duplicates in- John was jealous
o found 2 times
a found 2 times
s found 2 times
------------
Duplicates in- rats

Java program to find duplicate characters in a String using HashMap

If you are writing a Java program to find duplicate characters in a String and displaying the repetition count using HashMap then you can store each char of the String as a key and starting count as 1 which becomes the value. In each iteration check if key already exists, if yes then increment the count (by accessing the value for that key).

public class DuplicateChars {

  public static void main(String[] args) {    
    findDuplicateCharsWithCount("kakatua parrot is a bird");
    System.out.println("------------");
    findDuplicateCharsWithCount("John was jealous");
    System.out.println("------------");
    findDuplicateCharsWithCount("rats");
  }
    
  private static void findDuplicateCharsWithCount(String str) {
    System.out.println("Duplicates in- "+ str);
    char[] strArr = str.toCharArray();
    Map<Character, Integer> countMap = new HashMap<>();
    for(char c : strArr) {
      // We don't need to count spaces
      if(c == ' ')
        continue;
      if(countMap.containsKey(c)) {
        countMap.put(c, countMap.get(c) + 1);
      }else {
        countMap.put(c, 1);
      }
    }
    // Displaying the map values
    Set<Map.Entry<Character, Integer>> countSet = countMap.entrySet();
    for(Map.Entry<Character, Integer> entry  : countSet){
      if(entry.getValue() > 1) {
        System.out.println(entry.getKey() + " found " + entry.getValue() + " times");
      }
    }
  }
}

Output

Duplicates in- kakatua parrot is a bird
a found 5 times
r found 3 times
t found 2 times
i found 2 times
k found 2 times
------------
Duplicates in- John was jealous
a found 2 times
s found 2 times
o found 2 times
------------
Duplicates in- rats

Java program to find duplicate characters in a String using Java Stream

you can also use methods of Java Stream API to get duplicate characters in a String. There is a Collectors.groupingBy() method that can be used to group characters of the String, method returns a Map where character becomes key and value is the frequency of that charcter.

Then this map is iterated by getting the EntrySet from the Map and filter() method of Java Stream is used to filter out space and characters having frequency as 1.

Also note that chars() method of String class is used in the program which is available Java 9 onward. It is used to get String characters as IntStream.

import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class DuplicateCharCount {

  public static void main(String[] args) {
    String str = "kakatua parrot is a bird";
    duplicateCountInStream(str.chars());
  }
  
  private static void duplicateCountInStream(IntStream stream){
    Map<Character, Long> countMap = stream.mapToObj(c -> (char) c)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    countMap.entrySet().stream()
               .filter(es -> !es.getKey().equals(' ') && es.getValue() > 1)
               .forEach(es->{System.out.print("Character- " + es.getKey().toString() + " found ");

                   System.out.println(es.getValue() + " times");
                   });

  }
}

Output

Character- a found 5 times
Character- r found 3 times
Character- t found 2 times
Character- i found 2 times
Character- k found 2 times

That's all for this topic Find Duplicate Characters in a String With Repetition Count Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert String to Byte Array Java Program
  2. Add Double Quotes to a String Java Program
  3. Convert String to double in Java
  4. Java Program to Find First Non-Repeated Character in a Given String
  5. Unzip File in Java

You may also like-

  1. Compress And Decompress File Using GZIP Format in Java
  2. How to Create PDF in Java Using OpenPDF
  3. Producer-Consumer Java Program Using ArrayBlockingQueue
  4. Convert double to int in Java
  5. New Date And Time API in Java With Examples
  6. Exception Handling in Java Lambda Expressions
  7. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  8. Spring depends-on Attribute

Tuesday, January 4, 2022

Java Stream - boxed() With Examples

If you want to convert a stream of primitives int, long, double to a stream of respective wrapper objects i.e. Integer, Long, Double then Java Stream API has a boxed() method to do this job.

boxed() method in Java

In Java stream API there are primitive specializations of Stream named IntStream, LongStream and DoubleStream and each of these interfaces has a boxed() method that returns a Stream consisting of the elements of this stream, each boxed to an Integer, Long or Double respectively.

So, to summarize in java.util.stream.IntStream interface there is a boxed() method that returns a Stream consisting of the elements of this stream, each boxed to an Integer.

In java.util.stream.LongStream interface there is a boxed() method that returns a Stream consisting of the elements of this stream, each boxed to a Long.

In java.util.stream.DoubleStream interface there is a boxed() method that returns a Stream consisting of the elements of this stream, each boxed to a Double.

boxed() is an intermediate operation.

boxed stream Java examples

1. If you have a Stream of ints that you want to collect to a List. It won’t be possible to directly store primitive integers into a list so you will get compile time error for the following lines of code.

IntStream intStream = IntStream.of(1, 2, 3, 4, 5);
// Not able to collect primitives to a list 
intStream.collect(Collectors.toList());

In this scenario you can use boxed() to wrap primitive ints into Integer wrapper object which can than be stored into a List.

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

public class StreamBoxedDemo {
  public static void main(String[] args) {
    IntStream intStream = IntStream.of(1, 2, 3, 4, 5);
    List<Integer> numList = intStream.boxed().collect(Collectors.toList());
    System.out.println(numList);
  }
}

Output

[1, 2, 3, 4, 5]

2. Using boxed() method of LongStream to get a Stream consisting of the elements of this stream, each boxed to a Long.

public class StreamBoxedDemo {
  public static void main(String[] args) {
    List<Long> numList = LongStream.of(1, 2, 3, 4, 5)
                     .boxed().collect(Collectors.toList());
    System.out.println(numList);
  }
}

3. Using boxed() method of DoubleStream to get a Stream consisting of the elements of this stream, each boxed to a Double.

public class StreamBoxedDemo {
  public static void main(String[] args) {
    List<Double> numList = DoubleStream.of(1, 2, 3, 4, 5)
                      .boxed().collect(Collectors.toList());
    System.out.println(numList);
  }
}

That's all for this topic Java Stream - boxed() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - count() With Examples
  2. Java Stream - Collectors.groupingBy() With Examples
  3. Java Stream - findAny() With Examples
  4. Java Stream - distinct() With Examples
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Adding Tomcat Server to Eclipse
  2. PermGen Space Removal in Java 8
  3. Primitive Data Types in Java
  4. Type Wrapper Classes in Java
  5. Queue Implementation in Java Using Array
  6. Reading File in Java Using Files.lines And Files.newBufferedReader
  7. Angular Route Resolver - Passing Data Dynamically
  8. How to Read Properties File in Spring Framework

Monday, January 3, 2022

Java Stream - count() With Examples

In this tutorial you’ll learn about the count() method in the Java Stream API with the help of few examples.

count() method in Java

count() method returns the count of elements in the stream.

Syntax of count() method-

long count()

Some important points about count() method-

  1. It is a special case of a reduction operation which means it takes a sequence of input elements and reduce them into a single summary result.
  2. It is a terminal operation which means after count() operation the stream pipeline is considered consumed, and can no longer be used.

count() method Java examples

1. In the first example count() is used to get the count of elements in a List where List is used as a stream source.

public class StreamCountDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 5, 18, -11, 22, -8);
    long elementCount = numList.stream().count();
    System.out.println("Count of elements- " + elementCount);  
  }
}

Output

Count of elements- 6

2. Since count is a terminal operation so stream is considered closed after count operation but before count, intermediate operations like filter can be used to filter out certain elements and then get the count of the resulting stream. For example if we want count of positive elements in a list.

public class StreamCountDemo {

  public static void main(String[] args) {
    List<Integer> numList = Arrays.asList(7, 5, 18, -11, 22, -8);
    long elementCount = numList.stream().filter(n -> n > 0).count();
    System.out.println("Count of elements- " + elementCount);  
  }
}

Output

Count of elements- 4

3. In the following example count is used to get the count of employees having salary greater than 10000.

Employee class

public class Employee {
  private String empId;
  private int age;
  private String name;
  private char gender;
  private int salary;
  Employee(String empId, int age, String name, char gender, int salary){
    this.empId = empId;
    this.age = age;
    this.name = name;
    this.gender = gender;
    this.salary = salary;
  }
  public String getEmpId() {
    return empId;
  }

  public int getAge() {
    return age;
  }

  public String getName() {
    return name;
  }

  public char getGender() {
    return gender;
  }

  public int getSalary() {
    return salary;
  }
  @Override
  public String toString() {
      return "Emp Id: " +  getEmpId() + " Name: " + getName() + " Age: " + getAge();
  }
}
public class StreamCountDemo {

  public static void main(String[] args) {
    List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                new Employee("E002", 35, "Shelly", 'F', 7000), 
                new Employee("E003", 40, "Remington", 'M', 5000), 
                new Employee("E004", 37, "Bianca", 'F', 11000),
                new Employee("E005", 35, "Dominic", 'M', 7000), 
                new Employee("E006", 28, "Amanda", 'F', 14000));
    long elementCount = empList.stream().filter(e -> e.getSalary() > 10000).count();
    System.out.println("Count of elements- " + elementCount);  
  }
}

Output

Count of elements- 2

That's all for this topic Java Stream - count() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - boxed() With Examples
  2. Java Stream - sorted() With Examples
  3. Java Stream - distinct() With Examples
  4. Parallel Stream in Java Stream API
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Type Erasure in Java Generics
  2. SerialVersionUID And Versioning in Java Serialization
  3. Difference Between CountDownLatch And CyclicBarrier in Java
  4. Difference Between StackOverflowError and OutOfMemoryError in Java
  5. Docker Tutorial: Introduction to Docker
  6. Benefits, Disadvantages And Limitations of Autowiring in Spring
  7. Spring MVC JSON as Response Example
  8. Angular Access Control CanActivate Route Guard Example