Saturday, April 30, 2022

java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java

In this article we’ll see what is java.lang.UnsupportedClassVersionError and how to resolve UnsupportedClassVersionError in Java.

UnsupportedClassVersionError in Java

UnsupportedClassVersionError is thrown when the Java Virtual Machine attempts to read a class file whose major and minor version numbers are not supported by the current JVM version. In simpler terms you can say that this error is thrown when Java file is compiled by a higher version of Java compiler and you are trying to run the class file using a lower version of Java.

For example to show UnsupportedClassVersionError I have compiled a Java file using Java 12 and then tried to run it using Java 10 (lower version).

C:\Program Files\Java\jdk-10.0.1\bin>java -classpath F:\Anshu\NetJs\NetJS\src\  org.netjs.programs.FileByteRW
Error: LinkageError occurred while loading main class org.netjs.programs.FileByteRW
        java.lang.UnsupportedClassVersionError: org/netjs/programs/FileByteRW has been compiled by a more recent version of the Java Runtime 
  (class file version 56.0), this version of the Java Runtime only recognizes class file versions up to 54.0

Points about UnsupportedClassVersionError-

  1. It is an error which descends from java.lang.Error Since it is an error so you can’t do any exception handling to recover from it.
  2. This error is thrown at runtime.

Class file version – major and minor versions

Now the question is how does JVM determine whether the class file version is supported or not for that you have to know the class file format in Java.

Though a Java class file consists of 10 sections but there are only two sections that relate to UnsupportedClassVersionError-

  1. Magic Number which is the first 4 bytes of the class file and the value is 0xCAFEBABE. Magic number is used to uniquely identify the format.
  2. Version of class file format which are the next 4 bytes and contain the minor and major versions of the class file

If the class file version is greater that what JVM supports java.lang.UnsupportedClassVersionError is thrown.

Below table shows the major version number of the class file format being used for the Java versions. Reference - https://en.wikipedia.org/wiki/Java_class_file

Java Version Supported class version
Java SE 1761 (0x3D hex)
Java SE 1660 (0x3C hex)
Java SE 1559 (0x3B hex)
Java SE 1458 (0x3A hex)
Java SE 1357 (0x39 hex)
Java SE 1256 (0x38 hex)
Java SE 1155 (0x37 hex)
Java SE 1054 (0x36 hex)
Java SE 953 (0x35 hex)
Java SE 852 (0x34 hex)
Java SE 751 (0x33 hex)
Java SE 650 (0x32 hex)
Java SE 549 (0x31 hex)
JDK 1.448 (0x30 hex)
JDK 1.347 (0x2F hex)
JDK 1.246 (0x2E hex)
JDK 1.145 (0x2D hex)

How to resolve UnsupportedClassVersionError

Since UnsupportedClassVersionError is related to the Java version being used so there are two things that can be done based on what final Java version you want to use for your application.

  1. Compile code in an earlier version of Java if you want to supposr earlier version.
  2. Run Java code in a newer version by upgrading application Java version support.

In Eclips IDE you can reduce/increase the compiler compliance level based on your requirement. For that you need to go to Project properties – Java Compiler and then enable project specific settings to reduce or increase compiler compliance level.

Also change the configured JRE by going to Project properties – Java Build Path – libraries tab. There you can edit the chosen JRE and select an alternate JRE.

From commandline you can use --release option with javac to compile for a specific release. Supported releases are 7,8,9,10,11,12

That's all for this topic java.lang.UnsupportedClassVersionError - Resolving UnsupportedClassVersionError in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. java.lang.ClassCastException - Resolving ClassCastException in Java
  2. Java Exception Handling Tutorial
  3. throw Statement in Java Exception Handling
  4. Try-With-Resources in Java With Examples
  5. Java Exception Handling Interview Questions And Answers

You may also like-

  1. How to Sort ArrayList in Java
  2. Thread Priority in Java Multi-Threading
  3. Byte Streams in Java IO
  4. Array in Java With Examples
  5. Find Duplicate Elements in an Array Java Program
  6. Spring JdbcTemplate Select Query Example
  7. Python String isnumeric() Method
  8. Installing Hadoop on a Single Node Cluster in Pseudo-Distributed Mode

Friday, April 29, 2022

Spliterator in Java

Spliterator in Java, just like iterator, is used for traversing the elements of a source. The source of elements covered by a Spliterator could be, for example, an array, a Collection, an IO channel, or a generator function.

As the name suggests, Spliterator in Java can split the source and partition off some of its elements as another Spliterator, to be used in possibly-parallel operations. That way a huge data source can be divided into small sized units that can be traversed and processed in parallel.


Java Spliterator interface

Spliterator is a generic interface in Java defined as-

Interface Spliterator<T>

Where T is the type of elements returned by this Spliterator.

Java Spliterator methods

Though spliterator will increase performance by traversing the collection in parallel but you can also use spliterator even if you are not using parallel execution.

If you use iterator you have to use two methods hasNext() to ensure that there is next element and then next() method to use that element. Spliterator in Java provides methods that combine these two methods into one and making it more convenient to use. Some of the frequently used methods of Spliterator are-

  • tryAdvance()- If a remaining element exists, performs the given action on it, returning true; else returns false. Its form is-
    tryAdvance(Consumer<? super T> action)
    
    Here action is an instance of Consumer, which is a functional interface, it specifies the function that has to be applied on the next element while traversing the collection (or any other source).
  • forEachRemaining- Performs the given action for each remaining element, sequentially in the current thread, until all elements have been processed or the action throws an exception. Its form is-
    default void forEachRemaining(Consumer<? super T> action)
    
  • estimateSize()- Returns an estimate of the number of elements that would be encountered by forEachRemaining traversal, or returns Long.MAX_VALUE if infinite, unknown, or too expensive to compute. Its form is-
    long estimateSize()
    
  • trySplit()- If current spliterator can be partitioned a new spliterator is created, it partitions the elements of the source so that new spliterator traverse one of the partition while original spliterator traverses the other partition.
  • characteristics()- Returns a set of characteristics of this Spliterator and its elements.

Spliterator characteristics

A Spliterator also reports a set of characteristics() of its structure, source, and elements from among ORDERED, DISTINCT, SORTED, SIZED, NONNULL, IMMUTABLE, CONCURRENT, and SUBSIZED.

These characteristics are defined as constant fields in the Spliterator interface.

Read more about them here: https://docs.oracle.com/javase/8/docs/api/java/util/Spliterator.html#characteristics--

To see constant values- https://docs.oracle.com/javase/8/docs/api/constant-values.html#java.util.Spliterator

Using characteristics() method will give you a result represented as ORed values of the characterstics relevant for the given source.

Java Spliterator example

If you have a list of names and you want to iterate it and print the names, using iterator it can be done as follows-

public class IteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
    "Nick", "Amy", "Desi", "Margo");
    Iterator<String> itr = nameList.iterator();
    while (itr.hasNext()) {
      System.out.println("name - " + itr.next());   
    }
  }
}

Same iteration of a List can be done using spliterator like this-

public class SpliteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
    "Nick", "Amy", "Desi", "Margo");
    Spliterator<String> splitStr = nameList.spliterator();
    while(splitStr.tryAdvance((n) -> System.out.println("name - " + n)));
  }
}

You can see, with Spliterator, you need to use only one method tryAdvance() which combines both hasNext() and next() methods of the iterator.

Java Spliterator forEachRemaining method example

If you want to convert all the names to lowercase you can use forEachRemaining method.

import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;

public class SpliteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
      "Nick", "Amy", "Desi", "Margo");
    Spliterator<String> splitStr = nameList.spliterator();
    splitStr.forEachRemaining((n) -> {
      String x = n.toLowerCase();
      System.out.println("" + x);
    });
  }
}

Java Spliterator trySplit method example

If you want to split the original spliterator so that you can traverse the element in parallel.

import java.util.Arrays;
import java.util.List;
import java.util.Spliterator;

public class SpliteratorDemo {
  public static void main(String[] args) {
    List<String> nameList = Arrays.asList("Ram", "Sheila", "Mukesh", "Rani", 
      "Nick", "Amy", "Desi", "Margo");
    Spliterator<String> splitStr = nameList.spliterator();
    Spliterator<String> splitStr2 = splitStr.trySplit();
    // Check if splitting actually happened, then use it
    if(splitStr2 != null){
      System.out.println("Spliterator-2");
      while(splitStr2.tryAdvance((n) -> System.out.println("name - " + n)));
    }
    // Original spliterator
    System.out.println("Original Spliterator");
    while(splitStr.tryAdvance((n) -> System.out.println("name - " + n)));
  }        
}

Output

Spliterator-2
name - Ram
name - Sheila
name - Mukesh
name - Rani
Original Spliterator
name - Nick
name - Amy
name - Desi
name - Margo

When you are splitting the spliterator, make sure to check that splitting actually happened by checking for null.

Here note one thing, according to Java docs-

If the original thread hands a spliterator off to another thread for processing, it is best if that handoff occurs before any elements are consumed with tryAdvance(), as certain guarantees (such as the accuracy of estimateSize() for SIZED spliterators) are only valid before traversal has begun.

So make sure you first do the splitting then only start any operation on the elements.

Reference- https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/Spliterator.html

That's all for this topic Spliterator in Java. 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 API Tutorial
  2. Java Stream API Examples
  3. Primitive Type Streams in Java Stream API
  4. collect() Method And Collectors Class in Java Stream API
  5. Java Stream - Collectors.partitioningBy() With Examples

You may also like-

  1. Method Reference in Java
  2. Interface Static Methods in Java
  3. Deadlock in Java Multi-Threading
  4. Java CyclicBarrier With Examples
  5. CopyOnWriteArrayList in Java With Examples
  6. TreeMap in Java With Examples
  7. Difference Between Comparable and Comparator in Java
  8. Exception Propagation in Java Exception Handling

Thursday, April 28, 2022

How to Sort ArrayList in Java

In ArrayList elements are added in sequential order and while displaying the elements by iterating an arraylist that same default ordering will be used. Sometimes you may have a requirement to sort an ArrayList in Java in ascending or descending order. In this post we'll see how to sort an ArrayList of Strings, Integers or Dates in Java.


Options for sorting a List

You can sort an ArrayList using-

  1. sort() method of the List interface Java 8 onward. Note that sort() method is implemented as a default interface method in List interface.
    • default void sort(Comparator<? super E> c)- Sorts this list according to the order induced by the specified Comparator. If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements' natural ordering should be used.
  2. Using Collections.sort() method. There are two overloaded versions of sort method and according to Java docs their description is-
    • public static <T extends Comparable<? super T>> void sort(List<T> list)- Sorts the specified list into ascending order, according to the natural ordering of its elements. All elements in the list must implement the Comparable interface. Furthermore, all elements in the list must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

    • public static <T> void sort(List<T> list, Comparator<? super T> c)- Sorts the specified list according to the order induced by the specified comparator. All elements in the list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2)must not throw a ClassCastException for any elements e1 and e2 in the list).
  3. Using sorted method of the Java Stream API. There are two overloaded variants of the sorted method.
    • sorted()- Returns a stream consisting of the elements of this stream, sorted according to natural order.
    • sorted(Comparator<? super T> comparator)- Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

Sorting ArrayList of strings using sort() method of List

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = new ArrayList<>();
    cityList.add("Delhi");
    cityList.add("Mumbai");
    cityList.add("Bangalore");
    cityList.add("Chennai");
    cityList.add("Kolkata");
    cityList.add("Mumbai");
    // Passing null so natural ordering is used
    cityList.sort(null);
    System.out.println("List sorted using natural ordering" + cityList);
    
    // Using naturalOrder method to sort in natural order
    cityList.sort(Comparator.naturalOrder());
    System.out.println("List sorted using natural ordering" + cityList);
    
    // Using reverseOrder method to impose reverse of natural ordering
    cityList.sort(Comparator.reverseOrder());
    System.out.println("List sorted in reverse" + cityList);
  }
}

Output

List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted in reverse[Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Using Collections.sort() method to sort ArrayList

To sort an ArrayList of strings according to the natural ordering of its elements we can use the first of the two sort methods.

Collections.sort(List<T> list)
public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
    // sorting the list
    Collections.sort(cityList);
    System.out.println("List sorted using natural ordering" + cityList);
  }
}

Output

List sorted using natural ordering[Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]

As you can see you just need to pass the ArrayList to sort method. Collections.sort will work in this case because String class implements Comparable interface and provides implementation for the method compareTo(String anotherString).

Same way Integer class or Date class also implements Comparable interface so list of integers (or dates) can also be sorted in natural order by using sort() method of the Collections class or by using sort() method of the List interface. In fact Java docs give a list of all the classes that implements comparable interface thus can be used with the sort method to sort the elements in the natural order.

Classes Implementing Comparable

Following is the list of classes that already implement Comparable interface in Java. Thus the ArrayList storing obejcts of any of these classes can be sorted in its natural ordering by passing the list to sort() method.

Class Natural Ordering
Byte Signed numerical
Character Unsigned numerical
Long Signed numerical
Integer Signed numerical
Short Signed numerical
Double Signed numerical
Float Signed numerical
BigInteger Signed numerical
BigDecimal Signed numerical
Boolean Boolean.FALSE < Boolean.TRUE
File System-dependent lexicographic on path name
String Lexicographic
Date Chronological
CollationKey Locale-specific lexicographic

Sorting an ArrayList of strings in descending order

Collections.sort() method always sorts ArrayList of strings in ascending order. For sorting an ArrayList in descending order you need to use the second sort method which takes two parameters. First is the list that has to be sorted and second a comparator class that can be used to allow precise control over the sort order.
For sorting an ArrayList in descending order there are two options,

  • Use method reverseOrder() provided by Collections class itself

    General form and description

    public static <T> Comparator<T> reverseOrder()
    
    Returns a comparator that imposes the reverse of the natural ordering on a collection of objects that implement the Comparable interface.
  • Using a custom comparator.

Sorting ArrayList in descending order using reverseOrder method

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
     // sorting the list in descending order
    Collections.sort(cityList, Collections.reverseOrder());
    System.out.println("List sorted in reverses order- " + cityList);
  }
}

Output

List sorted in reverses order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Sorting ArrayList in descending order using custom Comparator

Internally reverseOrder method calls a Comparator class to sort the list in reverse order. We can do it ourselves too by writing our own comparator class.

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
     // sorting the list in descending order
    Collections.sort(cityList, (String a, String b)->  b.compareTo(a));
    System.out.println("List sorted in reverses order- " + cityList);
  }
}

Output

List sorted in reverses order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

Note that Comparator is implemented as a lambda expression here.

Sorting Java ArrayList using sorted method of the Java Stream

public class SortListDemo {
  public static void main(String[] args) {
    List<String> cityList = Arrays.asList("Delhi","Mumbai","Bangalore","Chennai","Kolkata","Mumbai");
    List<String> tempList = cityList.stream().sorted().collect(Collectors.toList());
    System.out.println("List sorted in natural order- " + tempList);
    tempList = cityList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    System.out.println("List sorted in reverse order- " + tempList);
  }
}

Output

List sorted in natural order- [Bangalore, Chennai, Delhi, Kolkata, Mumbai, Mumbai]
List sorted in reverse order- [Mumbai, Mumbai, Kolkata, Delhi, Chennai, Bangalore]

That's all for this topic How to Sort ArrayList in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. How ArrayList Works Internally in Java
  2. How to Join Lists in Java
  3. How to Remove Duplicate Elements From an ArrayList in Java
  4. Difference Between Comparable and Comparator in Java
  5. Java Collections Interview Questions And Answers

You may also like-

  1. Fail-Fast Vs Fail-Safe Iterator in Java
  2. How to Iterate a HashMap of ArrayLists of String in Java
  3. static import in Java
  4. Interface Static Methods in Java
  5. Method Reference in Java
  6. Count Number of Times Each Character Appears in a String Java Program
  7. Java ThreadLocal Class With Examples
  8. Try-With-Resources in Java With Examples

Wednesday, April 27, 2022

Comparing Two Strings in Python

For comparing two strings in Python you can use relational operators (==, <, <=, >, >=, !=). Using these operators content of the Strings is compared in lexicographical order and boolean value true or false is returned.

Note that for equality comparison use ‘==’ not 'is' operator as 'is' operator does the identity comparison (compares the memory location of the String objects).

Python String comparison

When Strings are compared in Python, comparison is done character by character.

Checking for equality using ‘==’

def check_equality(str1, str2):
  #using string slicing
  str = str1[8: :]
  print('String is ',str)
  if str == str2:
    print('Strings are equal')
  else:
    print('Strings are not equal')

str1 = "This is Python"
str2 = "Python"
check_equality(str1, str2)

Output

String is Python
Strings are equal

In the example using Python string slicing, a slice of the string is obtained which is then compared with another string for equality.

If you use ‘is’ operator, comparison returns false even if the content is same as in that case memory location of the objects is compared.

def check_equality(str1, str2):
  #using string slicing
  str = str1[8: :]
  print('String is', str)
  if str is str2:
    print('Strings are equal')
  else:
    print('Strings are not equal')

str1 = "This is Python"
str2 = "Python"
check_equality(str1, str2)

Output


String is Python
Strings are not equal

Python String comparison examples

Let’s see another example with other operators.

def check_equality(str1, str2):
  if str1 > str2:
    print(str1, 'is greater than', str2)

  if str1 < str2:
    print(str1, 'is less than', str2)

  if str1 != str2:
    print(str1, 'is not equal to', str2)

str1 = "This"
str2 = "That"
check_equality(str1, str2)

Output

This is greater than That
This is not equal to That

In the example following condition

if str1 < str2:
  print(str1, 'is less than', str2)

returns false so the message accompanying this condition is not displayed.

That's all for this topic Comparing Two Strings in Python. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Python Tutorial Page


Related Topics

  1. Check if String Present in Another String in Python
  2. Removing Spaces From String in Python
  3. Python Program to Reverse a String
  4. Nonlocal Keyword in Python With Examples
  5. Method Overriding in Python

You may also like-

  1. Name Mangling in Python
  2. Python for Loop With Examples
  3. self in Python
  4. Named Tuple in Python
  5. Switch Case Statement in Java With Examples
  6. Linear Search (Sequential Search) Java Program
  7. Dependency Injection in Spring Framework
  8. Difference Between @Controller And @RestController Annotations in Spring

Tuesday, April 26, 2022

How to Display Pyramid Patterns in Java - Part2

In the first part How to display pyramid patterns in Java - Part1 we have already seen Java programs for displaying some of the pyramid patterns using numbers and special symbols. In this post java programs are provided for some of the other pyramid patterns using numbers.

Java code for number pattern - Pattern 1

1
12
123
1234
12345
123456
12345
1234
123
12
1

For this types of patterns it is simpler to have to separate for loops. One for the increasing part and another for the decreasing part. In each of these loops there will be a nested for loop also.

import java.util.Scanner;

public class PatternsDemo {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter highest number for the pattern (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = 1; i <= num; i++){
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }            
      System.out.println();       
    }
    for(int i = num; i >= 1; i--){
      for(int j = 1; j < i; j++){
        System.out.print(j);
      }
      System.out.println();
    }                               
  }
}

Java code for number pattern - Pattern 2

1
22
333
4444
55555
666666
55555
4444
333
22
1
import java.util.Scanner;

public class PatternsDemo {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter highest number for the pattern (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = 1; i <= num; i++){
      for(int j = 1; j <= i; j++){
        System.out.print(i);
      }            
      System.out.println();            
    }
    for(int i = num ; i >= 1; i--){
      for(int j = 1; j < i; j++){
        System.out.print(i -1);
      }
      System.out.println();
    }                                
  }
}

Java code for number pattern - Pattern 3

999999999
88888888
7777777
666666
55555
4444
333
22
1
22
333
4444
55555
666666
7777777
88888888
999999999
import java.util.Scanner;

public class PatternsDemo {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter highest number for the pattern (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = num; i >= 1; i--){
      for(int j = 1; j <= i; j++){
        System.out.print(i);
      }            
      System.out.println();            
    }
    for(int i = 2 ; i <=num ; i++){
      for(int j = 1; j <= i; j++){
        System.out.print(i);
      }
      System.out.println();
    }                                
  }
}

Java code for number pattern - Pattern 4

1234567
123456
12345
1234
123
12
1
12
123
1234
12345
123456
1234567
public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = num; i >= 1; i--){
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }            
      System.out.println();            
    }
    for(int i = 2 ; i <=num ; i++){
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }
      System.out.println();
    }                                
  }
}

Java code for number pattern - Pattern 5

1234567
 123456
  12345
   1234
    123
     12
      1
     12
    123
   1234
  12345
 123456
1234567
public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = num; i >= 1; i--){
      for(int j = i; j < num; j++){
        System.out.print(" ");
      }  
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }            
      System.out.println();            
    }
    for(int i = 2 ; i <=num ; i++){
      for(int j = num; j > i; j--){
        System.out.print(" ");
      } 
      for(int j = 1; j <= i; j++){
        System.out.print(j);
      }
      System.out.println();
    }                                
  }
}

Java code for number pattern - Pattern 6

1 2 3 4 5 6 7 
 1 2 3 4 5 6 
  1 2 3 4 5 
   1 2 3 4 
    1 2 3 
     1 2 
      1 
     1 2 
    1 2 3 
   1 2 3 4 
  1 2 3 4 5 
 1 2 3 4 5 6 
1 2 3 4 5 6 7 
public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    // upper pyramid
    for(int i = num; i >= 1; i--){
      for(int j = 1; j <= num-i; j++){
        System.out.print(" ");
      }  
      for(int j = 1; j <= i; j++){
        System.out.print(j + " ");
      }            
      System.out.println(); 
    }
    //lower pyramid
    for(int i = 2 ; i <= num ; i++){
      for(int j=0; j< num-i; j++){
        System.out.print(" ");
      }
      for(int j = 1; j <= i; j++){
        System.out.print(j + " ");
      }
      System.out.println();
    }                                
  }
}

Java code for number pattern - Pattern 7

     1 
    1 2 
   1 2 3 
  1 2 3 4 
 1 2 3 4 5 
1 2 3 4 5 6 
 1 2 3 4 5 
  1 2 3 4 
   1 2 3 
    1 2 
     1 
public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    //upper pyramid
    for(int i = 1; i <= num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number
      for(int k = 1; k < i; k++){
        System.out.print(k + " ");
      }
      System.out.println(); 
    }
    for(int i = 1; i < num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < i; j++){
        System.out.print(" ");
      }
      // this loop will print the number
      for(int k = 1; k < num-i; k++){
        System.out.print(k + " ");
      }
      System.out.println(); 
    }  
  }
}

That's all for this topic How to Display Pyramid Patterns in Java - Part2. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Display Prime Numbers
  2. Armstrong Number or Not Java Program
  3. Factorial Program in Java
  4. Arrange Non-Negative Integers to Form Largest Number - Java Program
  5. Convert float to String in Java

You may also like-

  1. Zipping Files And Folders in Java
  2. Read or List All Files in a Folder in Java
  3. Format Date in Java Using SimpleDateFormat
  4. Find Maximum And Minimum Numbers in a Given Matrix Java Program
  5. Inheritance in Java
  6. Method Overriding in Java
  7. Type Casting in Java With Conversion Examples
  8. Ternary Operator in Java With Examples

Monday, April 25, 2022

How to Display Pyramid Patterns in Java - Part1

Writing a Java program to display a pyramid pattern is a good way to learn about nested loops. The pattern may contain numbers or any special symbol. So let's see some of the patterns and how to write a Java program to display those number or symbol patterns.

If you have noticed in most of the patterns one common thing is; it narrows down at the top (or bottom in case of reverse pyramid) for that you have to print that much spaces before printing the number(s).

Java code for pyramid of numbers - Pattern 1

    1
   2 2
  3 3 3
 4 4 4 4
5 5 5 5 5

In this pattern display count of a number is equal to the number in that row.

Logic is to have a loop that will iterate depending on the rows that are needed. Then there is a nested loop to display spaces. There is another nested loop to display the number.

import java.util.Scanner;

public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = 1; i <= num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number
      for(int k = 0; k < i; k++){
        System.out.print(i + " ");
      }
      System.out.println();           
    }           
  }
}

Java code for pyramid of stars - Pattern 2

     *
    * *
   * * *
  * * * *
 * * * * *
* * * * * *

The logic for this pattern is same as above, only change is instead of number asterisk (*) has to be displayed.

import java.util.Scanner;

public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = 1; i <= num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number
      for(int k = 0; k < i; k++){
        System.out.print("* ");
      }
      System.out.println();           
    }          
  }
}

Java code for number pattern - Pattern 3

     1
    1 2
   1 2 3
  1 2 3 4
 1 2 3 4 5
1 2 3 4 5 6

In this pyramid pattern instead of displaying the same number, numbers are displayed in ascending order in each row starting from 1.

import java.util.Scanner;

public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = 1; i <= num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number
      for(int k = 1; k < i; k++){
        System.out.print(k + " ");
      }
      System.out.println();        
    }            
  }
}

Java code for half pyramid pattern - Pattern 4

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9

This pattern is same as the pattern above minus the spaces. So the loop that prints the spaces is not needed.

import java.util.Scanner;

public class PatternsDemo {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = 1; i <= num; i++){
      
      // this loop will print the number
      for(int j = 1; j <= i; j++){
        System.out.print(j + " ");
      }
      System.out.println();      
    }            
  }
}

Java code for number pattern - Pattern 5

        1
       121
      12321
     1234321
    123454321
   12345654321
  1234567654321
 123456787654321
12345678987654321

Here rather than same number or in ascending order numbers are displayed in each row in both ascending and then descending order. That is why there is one more nested loop.

import java.util.Scanner;

public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = 1; i <= num; i++){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 0; j < num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number ascending part
      for(int k = 1; k < i; k++){
        System.out.print(k);
      }
      // this loop will print the number descending part
      for(int l = i; l >=1; l--){
        System.out.print(l);
      }
      System.out.println();            
    }           
  }
}

Java code for reverse pyramid pattern - Pattern 6

12345678987654321
 123456787654321
  1234567654321
   12345654321
    123454321
     1234321
      12321
       121
        1

This is the reverse pyramid which follows the same pattern as above but upside down.

import java.util.Scanner;

public class PatternsDemo {

  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = num; i >= 1; i--){
      // this loop will print the spaces after which the
      // number has to be printed
      for(int j = 1; j <= num - i; j++){
        System.out.print(" ");
      }
      // this loop will print the number ascending part
      for(int k = 1; k < i; k++){
        System.out.print(k);
      }
      // this loop will print the number descending part
      for(int l = i; l >=1; l--){
        System.out.print(l);
      }            
      System.out.println();           
    }            
  }
}

Java code for pattern (Floyds Triangle) - Pattern 7

Triangle with consecutive numbers.

1 
2 3 
4 5 6 
7 8 9 10 
11 12 13 14 15 
16 17 18 19 20 21 
22 23 24 25 26 27 28 
29 30 31 32 33 34 35 36 
public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    int number = 1;
    for(int i = 1; i <= num; i++){                
      for(int j = 0; j < i; j++){
        System.out.print(number++ + " ");
      }
      System.out.println();               
    } 
  }
}

Java code for pattern - Pattern 8

1 2 3 4 5 6 7 
1 2 3 4 5 6 
1 2 3 4 5 
1 2 3 4 
1 2 3 
1 2 
1 
public class PatternsDemo {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter number of rows in the pyramid (1-9) - ");

    int noOfRows = sc.nextInt();
    // calling method
    printPattern(noOfRows);
  }
    
  private static void printPattern(int num){
    for(int i = 0; i < num; i++){      
      // this loop prints the number
      for(int j = 1; j <= num - i; j++){
        System.out.print(j + " ");
      }
      System.out.println();            
    }    
  }
}

That's all for this topic How to Display Pyramid Patterns in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Armstrong Number or Not Java Program
  2. Swap or Exchange Two Numbers Without Using Any Temporary Variable Java Program
  3. Java Program to Check Prime Number
  4. Fibonacci Series Program in Java
  5. Java Program to Find The Longest Palindrome in a Given String

You may also like-

  1. Add Double Quotes to a String Java Program
  2. Matrix Multiplication Java Program
  3. How to Convert Date to String in Java
  4. Array in Java
  5. Polymorphism in Java
  6. Varargs (Variable-length Arguments) in Java
  7. Difference Between ReentrantLock and Synchronized in Java
  8. Configuring DataSource in Spring Framework

Sunday, April 24, 2022

Compress And Decompress File Using GZIP Format in Java

In this post we'll see how to use GZIP to compress and decompress a file in Java. You will mainly use GZIP tool to compress and decompress files in Unix systems. Here note that you can only compress a single file using GZIP not multiple files residing in a folder.

Refer Creating Tar File And GZipping Multiple Files - Java Program to see how to gzip multiple files in Java.

Steps to gzip a file

In order to compress a file using GZIP in Java the steps are as follows-

  1. For reading the source file (file which has to be GZIPped) create a FileInputStream.
  2. Create a FileOutputStream to the target file (output GZIPped file).
  3. Create a GZIPOutputStream wrapping the FileOutputStream.
  4. Then you just need to read from the input stream and write to the output stream.

Steps to decompress a file

In order to decompress a file using GZIP in Java the steps are as follows-

  1. For reading the compressed file create a FileInputStream.
  2. Wrap that FileInputStream with in a GZIPInputStream.
  3. Create a FileOutputStream to the new file (created on decompressing GZIP file).
  4. Then you just need to read from the input stream and write to the output stream.

Java example for compressing and decompressing file in GZIP format

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipDemo {

 public static void main(String[] args) {
  // Path to file which is gzipped
  String SOURCE_FILE = "G:\\Test\\abc.txt";
  // Path to gzipped output files
  String GZIP_OUTPUT_FILE = "G:\\Test\\abc.gz";
  // File you get after decompressings
  String GZIP_NEW_FILE = "G:\\Test\\newabc.txt";
  
  GZipDemo gZipDemo = new GZipDemo();
  try {
   // Compressing a file
   gZipDemo.compressGZipFile(SOURCE_FILE, GZIP_OUTPUT_FILE);
   
   // decompressing a file
   gZipDemo.deCompressGZipFile(GZIP_OUTPUT_FILE, GZIP_NEW_FILE);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }

 }
 /**
  * Method to gzip a file
  * @param sourceFile
  * @param outputFile
  * @throws IOException
  */
 public void compressGZipFile(String sourceFile, String outputFile) 
    throws IOException{
  FileInputStream fis = new FileInputStream(sourceFile);
  FileOutputStream fos = new FileOutputStream(outputFile);
  GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(fos); 
  byte[] buffer = new byte[1024];
  int len;
  while((len = fis.read(buffer)) > 0){
   gZIPOutputStream.write(buffer, 0, len);
  }
  // Keep it in finally
  fis.close();
  gZIPOutputStream.close();
 }
 
 /**
  * Method to decompress a gzip file
  * @param gZippedFile
  * @param newFile
  * @throws IOException
  */
 public void deCompressGZipFile(String gZippedFile, String newFile) 
    throws IOException{
  FileInputStream fis = new FileInputStream(gZippedFile);
  GZIPInputStream gZIPInputStream = new GZIPInputStream(fis);
  FileOutputStream fos = new FileOutputStream(newFile);
  byte[] buffer = new byte[1024];
  int len;
  while((len = gZIPInputStream.read(buffer)) > 0){
   fos.write(buffer, 0, len);
  }
  // Keep it in finally
  fos.close();
  gZIPInputStream.close();
 }
}

That's all for this topic Compress And Decompress File Using GZIP Format in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. How to Untar a File in Java
  2. Zipping Files And Folders in Java
  3. Unzip File in Java
  4. Read or List All Files in a Folder in Java
  5. Write to a File in Java

You may also like-

  1. How to Create PDF From XML Using Apache FOP
  2. Producer-Consumer Java Program Using volatile
  3. How to Run Threads in Sequence in Java
  4. Comparing Enum to String in Java
  5. How HashMap Works Internally in Java
  6. Java Semaphore With Examples
  7. Serialization Proxy Pattern in Java
  8. Polymorphism in Java

Saturday, April 23, 2022

How to Inject Null And Empty String Values in Spring

This post shows how you can inject null or empty String as a value for any property in Spring framework.

Injecting empty string

If you are trying to inject an empty string as a value for any property in Spring then you can just pass "" as a value for that property.

As example

If you have an Employee class with name as field. Then you can use "" for name property.

If passed as a constructor argument then the configuration is as given below-

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <constructor-arg name="name" value="" />        
</bean> 

If passed as property then the configuration is as given below-

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <property name="name" value=""/>      
</bean>

Injecting null

If you need to inject null value for any field in Spring then use the special <null/> element for it, don’t use value=”null” because that will pass "null" as a String value.

So don’t do this-

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <constructor-arg name="name" value="null" />   
</bean>

Use <null/> element instead in your Spring configuration.

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <constructor-arg name="name">
    <null/>
  </constructor-arg>
</bean>

If passed as setter property-

<bean id="employeeBean" class="org.netjs.exp.Spring_Example.Employee">
  <property name="name"><null/></property>
</bean>

That's all for this topic How to Inject Null And Empty String Values in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Dependency Injection Using factory-method in Spring
  2. Wiring Collections in Spring
  3. Spring Expression Language (SpEL) With Examples
  4. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  5. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

You may also like-

  1. Spring Bean Life Cycle
  2. Spring Component Scan to Automatically Discover Beans
  3. How to Read Properties File in Spring Framework
  4. Spring Profiles With Examples
  5. How HashMap Internally Works in Java
  6. Java Reflection API Tutorial
  7. Initializer Block in Java
  8. What is Hadoop Distributed File System (HDFS)

Bucket Sort Program in Java

In this post we’ll see how to write Bucket sort program in Java. Bucket sort is one of the O(N) sorting algorithm like Radix sort and Counting sort. Since it runs in linear time (O(N)) so Bucket sort is faster than the comparison based algorithms like Merge Sort or Quick Sort.

Just like Counting sort, Bucket sort also makes some assumption about the input data beforehand like data should be uniformly distributed and should be with in a range.

How does Bucket sort work

Bucket sort works by assigning the input elements to different buckets and then sorting those buckets individually using any sorting technique like insertion sort so the elements in those buckets are sorted. After that merge the buckets to get the sorted output.

For distributing the elements to the buckets uniformly a good hash function is needed. The hash code given by hash function should also be an ordered hash such that if element i is greater than element j then hash(i) should also be greater than hash(j).

Let’s try to clarify working of bucket sort with an example where the elements in input array are with in the range 0..99- {47, 85, 10, 45, 16, 34, 67, 80, 34, 4, 0, 99}

Another array for buckets is needed. Let’s say we want that the elements having hash code 0-9 are put in bucket 0, 10-19 in bucket 1 ..... 90-99 in bucket 9 then we need an array of length 10 for buckets.

Since more than one element may be assigned to the same bucket so a list is needed at each index of the bucket array to store those elements.

With these requirement and the input array as shown above the structure should be as given below.

bucket sort in java

After sorting individual buckets you will have a structure as shown below.

Now starting from bucket 0 merge all the buckets to get the sorted output.

Bucket sort Java program

  1. Following the steps for bucket sort as explained above you need to create a bucket array and assign a List (preferably linked list) to each array index.
    List<Integer>[] buckets = new List[noOfBuckets];
    // Associate a list with each index 
    // in the bucket array         
    for(int i = 0; i < noOfBuckets; i++){
        buckets[i] = new LinkedList<>();
    }
  2. Distribute input elements to the buckets as per the calculated hash.
  3. Sort each bucket, for that sort() method of the Collections utility class is used in the program.
  4. Merge buckets, you can use the input array itself as output (sorted array) while merging the buckets.
    for(List<Integer> bucket : buckets){
      for(int num : bucket){
        intArr[i++] = num;
      }
    }
    
    Though outer and inner loops are used while merging but in the outer loop you are retrieving the list at each index and then iterating that list in the inner loop so effectively you are linearly traversing all the buckets which should take O(N) time.

Java code

public class BucketSort {
  public static void main(String[] args) {
    int[] intArr = {47, 85, 10, 45, 16, 34, 67, 80, 34, 4, 0, 99};
    //int[] intArr = {21,11,33,70,5,25,65,55};
    System.out.println("Original array- " + Arrays.toString(intArr));
    bucketSort(intArr, 10);
    System.out.println("Sorted array after bucket sort- " + Arrays.toString(intArr));
  }
    
  private static void bucketSort(int[] intArr, int noOfBuckets){
    // Create bucket array
    List<Integer>[] buckets = new List[noOfBuckets];
    // Associate a list with each index 
    // in the bucket array         
    for(int i = 0; i < noOfBuckets; i++){
      buckets[i] = new LinkedList<>();
    }
    // Assign numbers from array to the proper bucket
    // by using hashing function
    for(int num : intArr){
      //System.out.println("hash- " + hash(num));
      buckets[hash(num)].add(num);
    }
    // sort buckets
    for(List<Integer> bucket : buckets){
      Collections.sort(bucket);
    }
    int i = 0;
    // Merge buckets to get sorted array
    for(List<Integer> bucket : buckets){
      for(int num : bucket){
        intArr[i++] = num;
      }
    }
  }
    
  // A very simple hash function
  private static int hash(int num){
    return num/10;
  }
}

Output

Original array- [47, 85, 10, 45, 16, 34, 67, 80, 34, 4, 0, 99]
Sorted array after bucket sort- [0, 4, 10, 16, 34, 34, 45, 47, 67, 80, 85, 99]

Performance of Bucket Sort

Average time complexity of Bucket sort is considered O(n+k) where O(n) is the time spent in distributing elements across the buckets and sorting them and O(k) is the time spent in merging the buckets.

In worst case when most of the elements land in the same bucket time complexity is O(n2).

Space complexity of Bucket sort is O(n+k) as an auxiliary array of size k is needed for buckets. Each index of that bucket array holds reference to a list, total number of nodes in all those lists will be n making the total auxiliary space requirement as (n+k).

That's all for this topic Bucket Sort Program in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Selection Sort Program in Java
  2. Bubble Sort Program in Java
  3. How to Run a Shell Script From Java Program
  4. How to Remove Elements From an Array Java Program
  5. How to Sort Elements in Different Order in Java TreeSet

You may also like-

  1. How to Read Properties File in Java
  2. Creating PDF in Java Using iText
  3. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  4. How to Display Pyramid Patterns in Java - Part1
  5. collect() Method And Collectors Class in Java Stream API
  6. Transaction Management in Java-JDBC
  7. Association, Aggregation And Composition in Java
  8. Spring MVC Exception Handling - @ExceptionHandler And @ControllerAdvice Example

Friday, April 22, 2022

Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble()

Collectors Class in Java Stream API provides many useful utility methods that can be used with Java Streams. One such group of methods, which can be classified as Collectors.averaging methods produces the arithmetic mean of the stream elements. There are following averaging methods for types int, long and double respectively.

  1. public static <T> Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper)- This method is used to get average of stream of integers. If no elements are present, the result is 0.
  2. public static <T> Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper)- This method is used to get average of stream of longs. If no elements are present, the result is 0.
  3. public static <T> Collector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper)- This method is used to get average of stream of doubles. If no elements are present, the result is 0.

As you can notice the argument passed to these methods are of type ToIntFunction, ToLongFunction and ToDoubleFunction respectively. These are functional interfaces which are implemented to extract the property to be averaged meaning their implementation produces a int-valued, long-valued and double-valued result respectively.

Collectors.averagingInt() Java example

In this example we’ll get the average of the List elements where elements are of type Integer.

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

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Integer> numbers = Arrays.asList(16, 17, 32, 5, 3);
      double avg = numbers.stream().collect(Collectors.averagingInt(Integer::intValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 14.6

Collectors.averagingLong() Java example

In this example we’ll get the average of the List elements where elements are of type long.

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Long> numbers = Arrays.asList(16L, 17L, 32L, 5L, 3L);
      double avg = numbers.stream().collect(Collectors.averagingLong(Long::longValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 14.6

Collectors.averagingDouble() Java example

In this example we’ll get the average of the List elements where elements are of type double.

public class CollectorAveraging {

  public static void main(String[] args) {
      List<Double> numbers = Arrays.asList(16.87, 17.34, 23.45, 2.22, 3.67);
      double avg = numbers.stream().collect(Collectors.averagingDouble(Double::doubleValue));
      System.out.println("Average of the list elements- " + avg);
  }
}

Output

Average of the list elements- 12.709999999999999

Collectors.averagingInt with Custom Object Example

In this example we’ll use summing method to get the average of salaries for all the employees.

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

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                  new Employee("E002", 35, "Shelly", 'F', 8000), 
                  new Employee("E003", 24, "Mark", 'M', 9000), 
                  new Employee("E004", 37, "Ritu", 'F', 11000),
                  new Employee("E005", 32, "Anuj", 'M', 6000), 
                  new Employee("E006", 28, "Amy", 'F', 14000));
     double avg = empList.stream().collect(Collectors.averagingInt(Employee::getSalary));
     System.out.println("Average employee salary- " + avg);
  }
}

Output

Average employee salary- 8833.333333333334

That's all for this topic Java Stream - Collectors.averagingInt(), averagingLong(), averagingDouble(). 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 - Collectors.summingInt(), summingLong(), summingDouble()
  2. Java Stream - Collectors.joining() With Examples
  3. Java Stream - findFirst() With Examples
  4. Java Stream - noneMatch() With Examples
  5. Java Stream - limit() With Examples

You may also like-

  1. Reflection in Java - Getting Constructor Information
  2. Serialization Proxy Pattern in Java
  3. StringJoiner Class in Java With Examples
  4. Binary Tree Traversal Using Breadth First Search Java Program
  5. Java Collections Interview Questions And Answers
  6. Installing Anaconda Distribution On Windows
  7. Autowiring in Spring Using XML Configuration
  8. Spring Batch Processing With List of Objects in batchUpdate() Method

Thursday, April 21, 2022

Java Stream - Collectors.summingInt(), summingLong(), summingDouble()

Collectors Class in Java Stream API is an implementation of Collector interface and provides many useful operations that can be used with Java Streams. One such group of methods, which can be classified as Collectors.summing methods, is used to add the stream elements. There are following summing methods for types int, long and double respectively.

  1. public static <T> Collector<T,?,Integer> summingInt(ToIntFunction<? super T> mapper)- This method is used to get the sum of stream of ints, if there is no element in the stream then the result is 0.
  2. public static <T> Collector<T,?,Long> summingLong(ToLongFunction<? super T> mapper)- This method is used to get the sum of stream of longs, if there is no element in the stream then the result is 0.
  3. public static <T> Collector<T,?,Double> summingDouble(ToDoubleFunction<? super T> mapper)- This method is used to get the sum of stream of doubles, if there is no element in the stream then the result is 0.

As you can notice the argument passed to these methods are of type ToIntFunction, ToLongFunction and ToDoubleFunction respectively. These are functional interfaces which are implementd to extract the property to be summed meaning their implementation produces a int-valued, long-valued and double-valued result.

Collectors.summingInt() Java example

In this example we’ll get the sum of the List elements where elements are of type Integer.

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

public class CollectorSumming {

  public static void main(String[] args) {
    List<Integer> numbers = Arrays.asList(11, 5, 2, 10, 1);
      int sum = numbers.stream().collect(Collectors.summingInt(Integer::intValue));
      System.out.println("Sum of list elements: " + sum);

  }
}

Output

Sum of list elements: 29

Collectors.summingLong() Java example

In this example we’ll get the sum of the List elements where elements are of type Long.

public class CollectorSumming {

  public static void main(String[] args) {
    List<Long> numbers = Arrays.asList(11L, 5L, 2L, 10L, 1L);
      long sum = numbers.stream().collect(Collectors.summingLong(Long::longValue));
      System.out.println("Sum of list elements: " + sum);
  }
}

Output

Sum of list elements: 29

Collectors.summingDouble() Java example

In this example we’ll get the sum of the List elements where elements are of type Double.

public class CollectorSumming {

  public static void main(String[] args) {
    List<Double> numbers = Arrays.asList(11.5, 5.0, 2.65, 10.34, 7.89);
    double sum = numbers.stream().collect(Collectors.summingDouble(Double::doubleValue));
      System.out.println("Sum of list elements: " + sum);
  }
}

Output

Sum of list elements: 37.38

Collectors.summingInt with Custom Object Example

In this example we’ll use summing method to get the sum of salaries for all the employees.

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

  public static void main(String[] args) {
     List<Employee> empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000), 
                  new Employee("E002", 35, "Shelly", 'F', 8000), 
                  new Employee("E003", 24, "Mark", 'M', 9000), 
                  new Employee("E004", 37, "Ritu", 'F', 11000),
                  new Employee("E005", 32, "Anuj", 'M', 6000), 
                  new Employee("E006", 28, "Amy", 'F', 14000));
    int sum = empList.stream().collect(Collectors.summingInt(Employee::getSalary));
      System.out.println("Sum of employee salaries: " + sum);
  }
}

Output

Sum of employee salaries: 53000

That's all for this topic Java Stream - Collectors.summingInt(), summingLong(), summingDouble(). 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 - Collectors.averagingInt(), averagingLong(), averagingDouble()
  2. Java Stream - Collectors.teeing() With Examples
  3. Java Stream - Collectors.partitioningBy() With Examples
  4. Spliterator in Java
  5. Java Stream - limit() With Examples

You may also like-

  1. JVM Run-Time Data Areas - Java Memory Allocation
  2. Shallow Copy And Deep Copy in Java Object Cloning
  3. Is String Thread Safe in Java
  4. Java Program to Get Current Date and Time
  5. Angular First App - Hello world Example
  6. Java Application With User Input in Docker Container
  7. Spring MVC Pagination Example Using PagedListHolder
  8. Spring Boot Hello World Web Application Example