Saturday, 30 January 2021

Java12: CompactNumberFormat: Convert decimal number to compact form

CompactNumberFormat class is introduced in Java12 and is used to format a decimal number in its compact form. This compact form of a number is suitable to display large numbers where the display space is limited.

 

Is compact form of a number locale specific?

Yes, compact form of a number is locale specific. For example following table represents the compact form of a number 1000 in different locales.

 

Locale

Compact form

India

1 हज़ार

America

1K

German

1.000

 

How to get the compact form of a number?

Step 1: Get instance of CompactNumberFormat class.

NumberFormat indiaCompactFormat = NumberFormat.getCompactNumberInstance(new Locale("hi", "IN"), NumberFormat.Style.SHORT);

 

Step 2: Call format method with a decimal number as argument.

String indiaCompactFormatResult = indiaCompactFormat.format(1000);

 

Find the below working application.

 

CompactFormExample.java

package com.sample.app.numbers;

import java.text.NumberFormat;
import java.util.Locale;

public class CompactFormExample {

	public static void main(String args[]) {
		NumberFormat indiaCompactFormat = NumberFormat.getCompactNumberInstance(new Locale("hi", "IN"),
				NumberFormat.Style.SHORT);
		NumberFormat usCompactFormat = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
		NumberFormat germanCompactFormat = NumberFormat.getCompactNumberInstance(Locale.GERMAN,
				NumberFormat.Style.SHORT);

		String indiaCompactFormatResult = indiaCompactFormat.format(1000);
		String usCompactFormatResult = usCompactFormat.format(1000);
		String germanCompactFormatResult = germanCompactFormat.format(1000);

		System.out.println("locale\tcompactform");
		System.out.println("INDIA\t" + indiaCompactFormatResult);
		System.out.println("US\t" + usCompactFormatResult);
		System.out.println("GERMANY\t" + germanCompactFormatResult);
	}
}

 

Output

locale	compactform
INDIA	1 हज़ार
US	1K
GERMANY	1.000

 

Compact number styles

There are two styles supported.

a.   SHORT

b.   LONG

For example, a SHORT style compact number instance in the US locale formats 1000000  as "1M". However, a LONG style instance in same locale formats 10000 as "1 million".

 

Find the below working application.

 

CompactFormStylesExample.java

 

package com.sample.app.numbers;

import java.text.NumberFormat;
import java.util.Locale;

public class CompactFormStylesExample {
	public static void main(String args[]) {
		long thousand = 1000l;
		long tenThousand = 10000l;
		long oneLaksh = 100000l;
		long tenLaksh = 1000000l;
		long oneCrore = 10000000l;
		long tenCrore = 100000000l;
		long hundredCrore = 1000000000l;
		long thousandCrore = 10000000000l;

		NumberFormat usShortStyle = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
		NumberFormat usLongStyle = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.LONG);

		System.out.println("number\t\tshort_form\tlong_form");
		System.out.println(thousand + "\t\t" + usShortStyle.format(thousand) + "\t\t" + usLongStyle.format(thousand));
		System.out.println(
				tenThousand + "\t\t" + usShortStyle.format(tenThousand) + "\t\t" + usLongStyle.format(tenThousand));
		System.out.println(oneLaksh + "\t\t" + usShortStyle.format(oneLaksh) + "\t\t" + usLongStyle.format(oneLaksh));
		System.out.println(tenLaksh + "\t\t" + usShortStyle.format(tenLaksh) + "\t\t" + usLongStyle.format(tenLaksh));
		System.out.println(oneCrore + "\t" + usShortStyle.format(oneCrore) + "\t\t" + usLongStyle.format(oneCrore));
		System.out.println(tenCrore + "\t" + usShortStyle.format(tenCrore) + "\t\t" + usLongStyle.format(tenCrore));
		System.out.println(hundredCrore + "\t" + usShortStyle.format(hundredCrore) + "\t\t" + usLongStyle.format(hundredCrore));
		System.out.println(thousandCrore + "\t" + usShortStyle.format(thousandCrore) + "\t\t" + usLongStyle.format(thousandCrore));

		
	}

}


Output

number		short_form	long_form
1000		1K		1 thousand
10000		10K		10 thousand
100000		100K		100 thousand
1000000		1M		1 million
10000000	10M		10 million
100000000	100M		100 million
1000000000	1B		1 billion
10000000000	10B		10 billion

 

Reference

https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/text/CompactNumberFormat.html

http://unicode.org/reports/tr35/tr35-numbers.html#Compact_Number_Formats

 

 


 

  

Previous                                                    Next                                                    Home

Java12: Find mismatch in contents of two files

'java.nio.file.Files' class provide 'mismatch' method, it takes two files as input and finds and returns the position of the first mismatched byte in the content of two files, or -1L if there is no mismatch.

 

Signature

public static long mismatch​(Path path, Path path2) throws IOException

 

Parameters:

         path - the path to the first file

         path2 - the path to the second file

        

Returns:

the position of the first mismatch or -1L if no mismatch

 

When can two files are considered to be same?

Two files are considered to match if they satisfy one of the following conditions:

a.   The two paths locate the same file, even if two equal paths locate a file does not exist, or

b.   The two files are the same size, and every byte in the first file is identical to the corresponding byte in the second file.

 

Otherwise there is a mismatch between the two files and the value returned by this method is:

 

a.   The position of the first mismatched byte, or

b.   The size of the smaller file (in bytes) when the files are different sizes and every byte of the smaller file is identical to the corresponding byte of the larger file.

 

Find the below working application.

 

FileMismatchExample.java

package com.sample.app.files;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FileMismatchExample {

	private static void writeToFile(Path path, String content) throws IOException {
		Files.write(path, content.getBytes());
	}

	public static void main(String args[]) throws IOException {
		File file1 = File.createTempFile("file1", ".txt");
		File file2 = File.createTempFile("file2", ".txt");
		File file3 = File.createTempFile("file3", ".txt");

		String str1 = "Hello World";
		String str2 = "Helloworld";

		Path path1 = file1.toPath();
		Path path2 = file2.toPath();
		Path path3 = file3.toPath();

		writeToFile(path1, str1);
		writeToFile(path2, str1);
		writeToFile(path3, str2);

		long offset = Files.mismatch(path1, path2);
		if (offset == -1l) {
			System.out.println(path1 + " and " + path2 + " has same content");
		} else {
			System.out.println(path1 + " and " + path2 + " do not have same content. Mismatch found at byte " + offset);
		}

		offset = Files.mismatch(path1, path3);
		if (offset == -1l) {
			System.out.println(path1 + " and " + path3 + " has same content");
		} else {
			System.out.println(path1 + " and " + path3 + " do not have same content. Mismatch found at byte " + offset);
		}

	}

}

Sample output

/var/folders/tp/qybw2qy54t39ffn2l0grsdrc0000gp/T/file13438498583646993710.txt and /var/folders/tp/qybw2qy54t39ffn2l0grsdrc0000gp/T/file214420760322000149874.txt has same content
/var/folders/tp/qybw2qy54t39ffn2l0grsdrc0000gp/T/file13438498583646993710.txt and /var/folders/tp/qybw2qy54t39ffn2l0grsdrc0000gp/T/file313488649827910837929.txt do not have same content. Mismatch found at byte 5

Reference

https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/nio/file/Files.html#mismatch(java.nio.file.Path,java.nio.file.Path)

 




Previous                                                    Next                                                    Home

Java12: Transform a string

‘transform’ method takes a function as argument and apply this function to the string and return the result.

 

Signature

public <R> R transform(Function<? super String, ? extends R> f)

 

Example 1: Convert string to upper case and prepend 5 spaces.

str.transform(s -> s.toUpperCase().indent(5));

 

Example 2: Display a welcome message by converting user name to uppercase.

name.transform(s -> "Welcome Mr. " + s.toUpperCase());

 

Find the below working application.

 

StringTransformExample1.java

package com.sample.app.strings;

public class StringTransformExample1 {

	public static void main(String args[]) {
		String str = "aa123ajbd134aa";

		int noOfDigits = str.transform((s) -> {
			int count = 0;

			for (int i = 0; i < s.length(); i++) {
				if (Character.isDigit(s.charAt(i))) {
					count++;
				}
			}
			return count;
		});

		String stringInUpperCase = str.transform(s -> s.toUpperCase());
		String stringInUpperCasePlus5SpacesIndentation = str.transform(s -> s.toUpperCase().indent(5));

		String name = "Krishna";
		String welcomeMessage = name.transform(s -> "Welcome Mr. " + s.toUpperCase());

		System.out.println("noOfDigits : " + noOfDigits);
		System.out.println("stringInUpperCase : " + stringInUpperCase);
		System.out.println("stringInUpperCasePlus5SpacesIndentation : " + stringInUpperCasePlus5SpacesIndentation);
		System.out.println("welcomeMessage : " + welcomeMessage);
	}

}

Output

noOfDigits : 6
stringInUpperCase : AA123AJBD134AA
stringInUpperCasePlus5SpacesIndentation :      AA123AJBD134AA

welcomeMessage : Welcome Mr. KRISHNA

 

 

Previous                                                    Next                                                    Home

Java12: String indent method

Signature

public String indent(int n)

 

Description

Adjusts the indentation of each line of this string based on the value of n, and normalizes line termination characters.

If n == 0, then line remains unchnages.

If n > 0, then n spaces are inserted at the beginning of each line.

If n < 0, then n spaces are removed from the beginning of each line.

 

Example

StringIndentExample.java

package com.sample.app.strings;

public class StringIndentExample {

	public static void main(String args[]) {
		String str = "       Hello World";
		String noIndenation = str.indent(0);
		String indet5Spaces = str.indent(5);
		String indentNegative5Spaces = str.indent(-5);

		System.out.println(str);
		System.out.println(noIndenation);
		System.out.println(indet5Spaces);
		System.out.println(indentNegative5Spaces);

	}

}

Output

       Hello World
       Hello World

            Hello World

  Hello World


Example 2: Format json string.

{

"id": 123,

"name": {

"firstName" : "Krishna",

"lastName" : "Gurram"

}

}

 

Following snippet formats the json string using indent method.

private static String getIndentedString() {
	StringBuilder builder = new StringBuilder();
	builder.append("{\n");
	builder.append("\"id\": 123,".indent(2));
	builder.append("\"name\": {".indent(2));
	builder.append("\"firstName\" : \"Krishna\",".indent(4));
	builder.append("\"lastName\" : \"Gurram\"".indent(4));
	builder.append("}".indent(2));
	builder.append("}");

	return builder.toString();
}


StringIndentExample2.java

package com.sample.app.strings;

public class StringIndentExample2 {

	private static String getIndentedString() {
		StringBuilder builder = new StringBuilder();
		builder.append("{\n");
		builder.append("\"id\": 123,".indent(2));
		builder.append("\"name\": {".indent(2));
		builder.append("\"firstName\" : \"Krishna\",".indent(4));
		builder.append("\"lastName\" : \"Gurram\"".indent(4));
		builder.append("}".indent(2));
		builder.append("}");

		return builder.toString();
	}

	public static void main(String args[]) {
		String s = getIndentedString();
		System.out.println(s);
	}

}


Output

{
  "id": 123,
  "name": {
    "firstName" : "Krishna",
    "lastName" : "Gurram"
  }
}


Reference

https://openjdk.java.net/jeps/326

 

 

 




 

 

Previous                                                    Next                                                    Home

Java12: Teeing collectors

Teeing collector take two different collectors to transform the elements of a Stream and then merge the result.

 


Signature

public static <T,​R1,​R2,​R> Collector<T,​?,​R> teeing​(Collector<? super T,​?,​R1> downstream1, Collector<? super T,​?,​R2> downstream2, BiFunction<? super R1,​? super R2,​R> merger)

 

Type Parameters:

         T - the type of the input elements

         R1 - the result type of the first collector

         R2 - the result type of the second collector

         R - the final result type

Parameters:

         downstream1 - the first downstream collector

         downstream2 - the second downstream collector

         merger - the function which merges two results into the single one

Returns:

a Collector which aggregates the results of two supplied collectors.

 

Example

Following snippet finds minimum and maximum age of employees in a stream.

 

 

employeeAges.stream().collect(teeing(minBy(Integer::compareTo), maxBy(Integer::compareTo), (minAge, maxAge) -> {

         return new EmployeeMinMaxAge(minAge.get(), maxAge.get());

}));

 

Find the below working example.

 

EmployeeMinMaxAge.java

package com.sample.app.model;

public class EmployeeMinMaxAge {
	private int minAge;
	private int maxAge;

	public EmployeeMinMaxAge(int minAge, int maxAge) {
		super();
		this.minAge = minAge;
		this.maxAge = maxAge;
	}

	public int getMinAge() {
		return minAge;
	}

	public void setMinAge(int minAge) {
		this.minAge = minAge;
	}

	public int getMaxAge() {
		return maxAge;
	}

	public void setMaxAge(int maxAge) {
		this.maxAge = maxAge;
	}

	@Override
	public String toString() {
		return "EmployeeMinMaxAge [minAge=" + minAge + ", maxAge=" + maxAge + "]";
	}

}


TeeingExample.java

package com.sample.app.streams;

import static java.util.stream.Collectors.maxBy;
import static java.util.stream.Collectors.minBy;
import static java.util.stream.Collectors.teeing;

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

import com.sample.app.model.EmployeeMinMaxAge;

public class TeeingExample {

	public static void main(String args[]) {
		List<Integer> employeeAges = Arrays.asList(19, 23, 44, 35, 36, 65, 50, 43);

		EmployeeMinMaxAge empMinAndMaxAge = employeeAges.stream()
				.collect(teeing(minBy(Integer::compareTo), maxBy(Integer::compareTo), (minAge, maxAge) -> {
					return new EmployeeMinMaxAge(minAge.get(), maxAge.get());
				}));

		System.out.println(empMinAndMaxAge);
	}

}


Output

EmployeeMinMaxAge [minAge=19, maxAge=65]

 

You can download java12 examples from below link.

https://github.com/harikrishna553/java12-demo

 

 

Reference

https://docs.oracle.com/en/java/javase/12/docs/api/java.base/java/util/stream/Collectors.html#teeing(java.util.stream.Collector,java.util.stream.Collector,java.util.function.BiFunction)

Previous                                                    Next                                                    Home