Found 4336 Articles for Java 8

Java Program to change a file attribute to writable

Samual Sam
Updated on 30-Jul-2019 22:30:25

77 Views

Let’s say our file is “input.txt”, which is set read-only −File myFile = new File("input.txt"); myFile.createNewFile(); myFile.setReadOnly();Now, set the above file to writable −myFile.setWritable(true);After that, you can use canWrite() to check whether the file is writable or not.Example Live Demoimport java.io.File; public class Demo {    public static void main(String[] args) throws Exception {       File myFile = new File("input.txt");       myFile.createNewFile();       myFile.setReadOnly();       if (myFile.canWrite()) {          System.out.println("Writable!");       } else {          System.out.println("Read only mode!");       }       ... Read More

How to get the Checksum of a Byte Array in Java?

karthikeya Boyini
Updated on 30-Jul-2019 22:30:25

962 Views

Create a Byte Array for which you want the Checksum −byte[] arr = "This is it!".getBytes();Now, create a Checksum object −Checksum checksum = new Adler32(); checksum.update(arr, 0, arr.length);The update() above updates the current checksum with the specified array of bytes.Now, get the checksum with getValue() method, which gives the current checksum value.Example Live Demoimport java.util.zip.Adler32; import java.util.zip.Checksum; public class Demo {    public static void main(String[] argv) throws Exception {       byte[] arr = "This is it!".getBytes();       Checksum checksum = new Adler32();       checksum.update(arr, 0, arr.length);       long res = checksum.getValue();   ... Read More

How to extract multiple integers from a String in Java?

Samual Sam
Updated on 30-Jul-2019 22:30:25

494 Views

Let’s say the following is our string with integer and characters −String str = "(29, 12; 29, ) (45, 67; 78, 80)";Now, to extract integers, we will be using the following pattern −\dWe have set it with Pattern class −Matcher matcher = Pattern.compile("\d+").matcher(str);Example Live Demoimport java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo {    public static void main(String[] args) {       String str = "(29, 12; 29, ) (45, 67; 78, 80)";       Matcher matcher = Pattern.compile("\d+").matcher(str);       Listlist = new ArrayList();       while(matcher.find()) {          list.add(Integer.parseInt(matcher.group()));       }       System.out.println("Integers = "+list);    } }OutputIntegers = [29, 12, 29, 45, 67, 78, 80]

Java Program to get frequency of words with Lambda Expression

karthikeya Boyini
Updated on 30-Jul-2019 22:30:25

403 Views

Let’s say the following is the List −List list = Arrays.asList("Welcome", "to", "the", "club", "club", "the");No, let us create a Map to get the frequency of words. Here, we are using Lambda Expression as well −Map map = list    .parallelStream()    .flatMap(a -> Arrays.asList(a.split(" ")).stream())    .collect(    Collectors.toConcurrentMap(c ->c.toLowerCase(), c -> 1,    Integer::sum));Example Live Demoimport java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class Demo {    public static void main(String[] args) {       List list = Arrays.asList("Welcome", "to", "the", "club", "club", "the");       Map map = list          .parallelStream()   ... Read More

How to display numbers in scientific notation in Java?

Samual Sam
Updated on 30-Jul-2019 22:30:25

4K+ Views

To display number in scientific notation, create NumberFormat object first −NumberFormat numFormat = newDecimalFormat();Now, let’s say you need to format the minimum value of Integer −int i = Integer.MIN_VALUE; System.out.println(i); numFormat = newDecimalFormat("0.######E0"); System.out.println(numFormat.format(i)); numFormat = newDecimalFormat("0.#####E0"); System.out.println(numFormat.format(i));Above, we have used format() method of the NumberFormat class.Example Live Demoimport java.text.DecimalFormat; import java.text.NumberFormat; public class Demo {    public static void main(String args[]) {       NumberFormat numFormat = new DecimalFormat();       int i = Integer.MIN_VALUE;       System.out.println(i);       numFormat = new DecimalFormat("0.######E0");       System.out.println(numFormat.format(i));       numFormat = new DecimalFormat("0.#####E0");   ... Read More

Set Date value in Java HashMap?

karthikeya Boyini
Updated on 30-Jul-2019 22:30:25

1K+ Views

Create a Calendar instance and Date object −Calendar cal = Calendar.getInstance(); Date date = new Date(); cal.setTime(date);Now, create a HashMap and store Date value −LinkedHashMaphashMap = new LinkedHashMap(); hashMap.put("year", cal.get(Calendar.YEAR)); hashMap.put("month", cal.get(Calendar.MONTH)); hashMap.put("day", cal.get(Calendar.DAY_OF_MONTH));Example Live Demoimport java.util.Calendar; import java.util.Date; import java.util.LinkedHashMap; public class Demo {    public static void main(String[] argv) {       Calendar cal = Calendar.getInstance();       Date date = new Date();       System.out.println("Date = "+date);       cal.setTime(date);       LinkedHashMaphashMap = new LinkedHashMap();       hashMap.put("year", cal.get(Calendar.YEAR));       hashMap.put("month", cal.get(Calendar.MONTH));       hashMap.put("day", cal.get(Calendar.DAY_OF_MONTH));     ... Read More

How to display random numbers less than 20 in Java

Samual Sam
Updated on 30-Jul-2019 22:30:25

250 Views

At first, create a Random class object −Random rand = new Random();Now, create a new array −int num; int arr[] = new int[10];Loop through and set the Random nextInt with 20 as parameter since you want random numbers less than 20 −for (int j = 0; j

How to calculate the possibilities of duplication for random number within a range in Java

karthikeya Boyini
Updated on 30-Jul-2019 22:30:25

142 Views

To get the duplicate numbers for random numbers in a range, loop through and create two Random class objects −Use nextInt() to get the next number −intrandVal1 = new Random().nextInt(50); intrandVal2 = new Random().nextInt(50);Now, compare both the above numbers −if (randVal1 == randVal2) {    System.out.println("Duplicate number = "+randVal1); }All the above is to be done in a loop −for (int i = 1; i

Java Program to check if a Float is Infinite or Not a Number(NAN)

Samual Sam
Updated on 30-Jul-2019 22:30:25

2K+ Views

To check if a Float is isInfinite, use the isInfinite() method and to check for NAN, use the isNaN() method.Example Live Demopublic class Demo {    public static void main(String[] args) {       float value1 = (float) 1 / 0;       boolean res1 = Float.isInfinite(value1);       System.out.println("Checking for isInfinite? = "+res1);       float value2 = (float) Math.sqrt(9);       boolean res2 = Float.isNaN(value2);       System.out.println("Checking for isNan? = "+res2);    } }OutputChecking for isInfinite? = true Checking for isNan? = false

Java Program to get minutes between two time instants

karthikeya Boyini
Updated on 30-Jul-2019 22:30:25

424 Views

At first, create two time instants −Instant time1 = Instant.now(); Instant time2 = time1.plus(5, ChronoUnit.HOURS).plus(10, ChronoUnit.MINUTES);Use between() to get the minutes between two time instants −Duration duration = Duration.ofSeconds(13); Instant i = time1.plus(duration); System.out.println("Minutes between two time instants = "+Duration.between(time1, time2).toMinutes());Example Live Demoimport java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; public class Demo {    public static void main(String[] args) {       Instant time1 = Instant.now();       Instant time2 = time1.plus(5, ChronoUnit.HOURS).plus(10, ChronoUnit.MINUTES);       Duration duration = Duration.ofSeconds(13);       Instant i = time1.plus(duration);       System.out.println("Minutes between two time instants = "+Duration.between(time1, time2).toMinutes());   ... Read More

Advertisements