Java Tutorials for Freshers and Experience developers, Programming interview Questions, Data Structure and Algorithms interview Programs, Kotlin programs, String Programs, Java 8 Stream API, Spring Boot and Troubleshooting common issues.
الخميس، 17 يونيو 2021
Java 8 Stream Group By Count Example
الأربعاء، 16 يونيو 2021
Windows Grep Equivalent – findstr Examples for Grep Command
1. Overview
2. By Filtering the Results
// example of unix grep command to filter ls -l | grep javaprogramto // windows equivalent command dir | findstr javaprogramto
// example of unix grep command to filter ls -l | grep -iE "javaprogramto|kotlin" // windows equivalent command dir | findstr "javaprogramto kotlin"
3. By Searching the Files
#Example 1 #Linux - find the matches $ grep javaprogramto input.txt #Windows - find the matches c:\> findstr javaprogramto input.txt #Example 2 #Linux - count the matches $ grep -c javaprogramto input.txt #Windows - count the matches c:\> findstr -N javaprogramto input.txt
4. By Searching List Of Files
#Example 1 #Linux - search in folders $ grep javaprogramto -lr /path/folder #Windows - search in folder files c:\> findstr /M javaprogramto c:\folder\*
5. Help Command
#Example to get help from provider $ grep --help $ man grep #Windows c:\> findstr -?
6. Conclusion
الثلاثاء، 15 يونيو 2021
Spring Boot - How to Change Default Port in Spring Application?
1. Introduction
الاثنين، 14 يونيو 2021
Kotlin - Convert Map to List Examples
1. Overview
2. Converting HashMap to List in Kotlin Using ArrayList Constructor
package com.javaprogramto.kotlin.collections.map.list import java.util.HashMap fun main(array: Array<String>) { var map = HashMap<Int, String>(); map.put(10, "Ten") map.put(20, "Twenty") map.put(30, "Thirty") map.put(40, "Fourty") map.put(50, "Fifty") var keysList = ArrayList(map.keys); var valuesList = ArrayList(map.values); println("Keys list : $keysList") println("Values list : $valuesList") }
Keys list : [50, 20, 40, 10, 30] Values list : [Fifty, Twenty, Fourty, Ten, Thirty]
3. Converting LinkedHashMap to List in Kotlin Using ArrayList Constructor
package com.javaprogramto.kotlin.collections.map.list import java.util.HashMap fun main(array: Array<String>) { // to holds the insertion order var map = LinkedHashMap<Int, String>(); map.put(10, "Ten") map.put(20, "Twenty") map.put(30, "Thirty") map.put(40, "Fourty") map.put(50, "Fifty") // gets the keys and values as per the insertion var keysList = ArrayList(map.keys); var valuesList = ArrayList(map.values); // prints println("Keys list : $keysList") println("Values list : $valuesList") }
Keys list : [10, 20, 30, 40, 50] Values list : [Ten, Twenty, Thirty, Fourty, Fifty]
4. Kotlin Map to List using toList() method
package com.javaprogramto.kotlin.collections.map.list import java.util.HashMap fun main(array: Array<String>) { var map = HashMap<Int, String>(); map[10] = "Ten" map[20] = "Twenty" map[30] = "Thirty" map[40] = "Fourty" map[50] = "Fifty" // example 1 using toList() method var keysList = map.keys.toList(); var valuesList = map.values.toList(); println("using toList()") println("Keys list : $keysList") println("Values list : $valuesList") // example 2 using toList() method var mutableMap: MutableMap<Int, String> = HashMap() mutableMap[10] = "Ten" mutableMap[20] = "Twenty" mutableMap[30] = "Thirty" mutableMap[40] = "Fourty" mutableMap[50] = "Fifty" var entries = mutableMap.toList().map { "(${it.first}, ${it.second})"} println("\nusing toList() on mutable map") entries.forEach{print("$it ")} }
using toList() Keys list : [50, 20, 40, 10, 30] Values list : [Fifty, Twenty, Fourty, Ten, Thirty] using toList() on mutable map (50, Fifty) (20, Twenty) (40, Fourty) (10, Ten) (30, Thirty)
5. Kotlin Map to List using entries properties
package com.javaprogramto.kotlin.collections.map.list import java.util.HashMap fun main(array: Array<String>) { var mutableMap: MutableMap<Int, String> = HashMap() mutableMap[10] = "Ten" mutableMap[20] = "Twenty" mutableMap[30] = "Thirty" mutableMap[40] = "Fourty" mutableMap[50] = "Fifty" var list : List<String> = mutableMap.entries.map { ("${it.key} --> ${it.value}") } list.forEach{println(it)} }
50 --> Fifty 20 --> Twenty 40 --> Fourty 10 --> Ten 30 --> Thirty
6. Kotlin Map to List using keys and values
package com.javaprogramto.kotlin.collections.map.list import java.util.HashMap fun main(array: Array<String>) { var mutableMap: MutableMap<Int, String> = HashMap() mutableMap[10] = "Ten" mutableMap[20] = "Twenty" mutableMap[30] = "Thirty" mutableMap[40] = "Fourty" mutableMap[50] = "Fifty" var keysList : List<String> = mutableMap.keys.map { ("${it} ") } var valuesList : List<String> = mutableMap.values.map { ("${it} ") } println("---- keys list ------") keysList.forEach{println(it)} println("----- values list ------") valuesList.forEach{println(it)} }
---- keys list ------ 50 20 40 10 30 ----- values list ------ Fifty Twenty Fourty Ten Thirty
7. Conclusion
الأحد، 13 يونيو 2021
Java 8 IntStream With Working Examples
1. Overview
- IntStream Creation
- ForEach loop
- IntStream ranges
- IntStream min and max
- IntStream find
- IntStrem map
- IntStream filter
- IntStream distinct
- IntStream to Array
- IntStream to List
2. Creating IntStream
- IntStream.of()
- IntStream.range()
- IntStream.rangeclosed()
- IntStream.generate()
- IntStream.iterate()
2.1 IntStream.of()
package com.javaprogramto.java8.intstream; import java.util.stream.IntStream; public class IntStreamOf { public static void main(String[] args) { IntStream singleValue = IntStream.of(10); IntStream multipleValeus = IntStream.of(1, 5, 10, 20, 30); } }
2.2 IntStream.range()
IntStream range10to30 = IntStream.range(10, 20);
2.3 IntStream.rangeclosed()
IntStream range10to15closed = IntStream.range(10, 15);
2.4 IntStream.generate()
IntStream random = IntStream.generate( () -> { return (int) Math.random() * 5000;});
2.5 IntStream.iterate()
IntStream iterate = IntStream.iterate(1000, i -> i + 4000).limit(5);
3. IntStream forEach()
package com.javaprogramto.java8.intstream; import java.util.stream.IntStream; public class IntStreamOf { public static void main(String[] args) { System.out.println("for loop"); for(int i = 1000; i < 20000 ; i = i + 4000) { print(i); } System.out.println("intstream foreach loop"); IntStream iterate = IntStream.iterate(1000, i -> i + 4000).limit(5); iterate.forEach(n -> print(n)); } private static void print(int n) { System.out.println(n); } }
4. IntStream ranges
IntStream range10to15range = IntStream.range(10, 15); IntStream range10to15closed = IntStream.rangeClosed(10, 15); System.out.println("range(10, 15) : "+Arrays.toString(range10to15range.toArray())); System.out.println("rangeClosed(10, 15) : "+Arrays.toString(range10to15closed.toArray()));
range(10, 15) : [10, 11, 12, 13, 14] rangeClosed(10, 15) : [10, 11, 12, 13, 14, 15]
5. IntStream min and max
System.out.println("range(10, 15) min value : "+IntStream.range(10, 15).min().getAsInt()); System.out.println("range(10, 15) max value : "+IntStream.range(10, 15).max().getAsInt());
range(10, 15) min value : 10 range(10, 15) max value : 14
6. IntStream find value
System.out.println("findFirst value : "+IntStream.iterate(10, i -> i + 2).limit(100).findFirst().getAsInt()); System.out.println("findAny value : "+IntStream.iterate(10, i -> i + 2).limit(100).findAny().getAsInt()); System.out.println("parallel findAny value : "+IntStream.iterate(10, i -> i + 2).limit(100).parallel().findAny().getAsInt());
findFirst value : 10 findAny value : 10 parallel findAny value : 160
7. IntStream map() or flatMap()
IntStream mapInput = IntStream.iterate(10, i -> i + 1).limit(10); System.out.println("map input stream : "+Arrays.toString(mapInput.toArray())); IntStream mapOutput = mapInput.map( i -> i * 2); System.out.println("map Output stream : "+Arrays.toString(mapOutput.toArray())); IntStream input1 = IntStream.iterate(10, i -> i + 1).limit(10); System.out.println("flat map : "+Arrays.toString(input1.flatMap( i -> IntStream.of(i)).toArray()));
map input stream : [10, 11, 12, 13, 14, 15, 16, 17, 18, 19] map Output stream : [20, 22, 24, 26, 28, 30, 32, 34, 36, 38] flat map : [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
8. IntStream filter
IntStream stream = IntStream.range(100, 200); // filter by number divisible by 5 and 7 System.out.println("numbers divisible by 5 and 7 are : "); stream.filter(i -> (i % 5 == 0 && i % 7 == 0)).forEach(System.out::println); IntStream stream2 = IntStream.range(100, 200); List<Integer> primes = stream2.filter(IntStreamOf::checkPrime).boxed().collect(Collectors.toList()); System.out.println("Prime numbers (100, 200) are "+primes);
numbers divisible by 5 and 7 are : 105 140 175 Prime numbers (100, 200) are [101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199]
9. IntStream distinct()
Arrays.toString(IntStream.of(1, 2, 3, 1, 2, 3).distinct().toArray());
[1, 2, 3]
10. IntStream to Array and List or Set
int[] intArray = IntStream.of(1, 2, 3, 1, 2, 3).toArray(); System.out.println("int array : "+Arrays.toString(intArray)); List<Integer> list = IntStream.of(1, 2, 3, 1, 2, 3).boxed().collect(Collectors.toList()); System.out.println("IntStream to List : "+list); Set<Integer> set = IntStream.of(1, 2, 3, 1, 2, 3).boxed().collect(Collectors.toSet()); System.out.println("IntStream to Set : "+set);
11. Conclusion
How to compare two ArrayList for equality in Java 8? ArrayList equals() or containsAll() methods works?
1. Introduction
In this article, We'll learn how to compare two ArrayLists for checking Objects equality.
ArrayList has an equal() method that takes one argument type of Object. This equals() method compares the passed list object with the current list object. If both lists are having same values then it returns true, otherwise false. equals()
Read more on how to compare two strings lexicographically.
Example programs are shown on equals(), containsAll() and java 8 Stream API.
Java - How to Convert Java Array to Iterable?
1. Overview
2. Create a iterator over the array using loops
package com.javaprogramto.arrays.toiterabale; /** * * Array Iterate example using loops * * @author javaprogramto.com * */ public class ArrayIterate { public static void main(String[] args) { // string array String[] names = new String[] {"john", "Amal", "Paul"}; // iterating array over its values. for(int index=0; index< names.length ; index++) { System.out.println(names[index]); } } }
john Amal Paul
3. Convert Java Array to Iterable using legacy java before JDK 8
package com.javaprogramto.arrays.toiterabale; import java.util.Arrays; import java.util.Iterator; import java.util.List; /** * * Example to convert Java Array to Iterable before Java 8 * * @author javaprogramto.com * */ public class JavaArrayToIterableExample { public static void main(String[] args) { // string array String[] names = new String[] {"john", "Amal", "Paul"}; // string array to list conversion List<String> namesList = Arrays.asList(names); // List to iterable Iterator<String> it = namesList.iterator(); // printing each value from iterator. while(it.hasNext()) { System.out.println(it.next()); } } }
john Amal Paul
4. Convert Java Array to Iterable Using Java 8 Stream
import java.util.Arrays; import java.util.Iterator; import java.util.stream.Stream; /** * * Example to convert Java Array to Iterable using Java 8 Arrays.stream() * * @author javaprogramto.com * */ public class JavaArrayToIterableExampleJava8 { public static void main(String[] args) { // string array String[] names = new String[] {"john", "Amal", "Paul"}; System.out.println("Multi line solution"); // Convert string array to Stream<String> Stream<String> namesList = Arrays.stream(names); // Stream to iterable Iterator<String> it = namesList.iterator(); // printing each value from iterator. while(it.hasNext()) { System.out.println(it.next()); } // singel line System.out.println("\nIn single line"); Arrays.stream(names).iterator().forEachRemaining(name -> System.out.println(name)); } }
Multi line solution john Amal Paul In single line john Amal Paul
5. Bonus - Convert String to Iterable
public class JavaStringToIterableExampleJava9 { public static void main(String[] args) { // string String numbers = "1 2 3 4 5 6"; // string to string array String[] numbersArray = numbers.split(" "); System.out.println("Multi line solution"); // Convert string array to Stream<String> Stream<String> numbersList = Arrays.stream(numbersArray); // Stream to iterable Iterator<String> it = numbersList.iterator(); // printing each value from iterator. while(it.hasNext()) { System.out.println(it.next()); } // singel line System.out.println("\nIn single line"); Arrays.stream(numbersArray).iterator().forEachRemaining(name -> System.out.println(name)); } }
Multi line solution 1 2 3 4 5 6 In single line 1 2 3 4 5 6
6. Conclusion
الاثنين، 7 يونيو 2021
Java Convert File Contents to String
1. Overview
الجمعة، 4 يونيو 2021
Java - How to Delete Files and Folders?
1. Overview
In this tutorial, We will learn how to delete the files and folders in java.
Let us learn the example programs on file deletion and folder removal in java.
2. Java Files Delete Example
First, Use delete() method on the file object to delete the file. Returns true if the file is delete successfully and else return false if there are any failures.
In the below program, we have taken two files test.log file is present in the location and no-file.log does not exists on the location.
Let us see the behaviour of delete() method.
package com.javaprogramto.files.delete; import java.io.File; /** * How to delete the file in java using File api delete() method. * * @author JavaProgramTo.com * */ public class FileDelete { public static void main(String[] args) { // File deletion success String fileName = "src/main/java/com/javaprogramto/files/delete/test.log"; File file = new File(fileName); boolean isFileDeleted = file.delete(); if(isFileDeleted) { System.out.println("File deleted without any errors for "+fileName); } else { System.out.println("File deletion is failed"); } // File deletion error. fileName = "src/main/java/com/javaprogramto/files/delete/no-file.log"; file = new File(fileName); isFileDeleted = file.delete(); if(isFileDeleted) { System.out.println("File deleted without any errors for "+fileName); } else { System.out.println("File deletion is failed for "+fileName); } } }
Output:
File deleted without any errors for src/main/java/com/javaprogramto/files/delete/test.log File deletion is failed for src/main/java/com/javaprogramto/files/delete/no-file.log
3. Java Delete Folder Example
Next, we will try to delete the folder which is having the files and next empty folder deletion using delete() method.
package com.javaprogramto.files.delete; import java.io.File; /** * How to delete the folder in java using File API delete() method. * * @author JavaProgramTo.com * */ public class FileDeleteFolder { public static void main(String[] args) { // Folder deletion not done String folderName = "src/main/java/com/javaprogramto/files/delete"; File file = new File(folderName); boolean isFileDeleted = file.delete(); if(isFileDeleted) { System.out.println("Folder with files is deleted"); } else { System.out.println("Folder with files is not deleted"); } // Empty Folder deletion success . folderName = "src/main/java/com/javaprogramto/files/emptyfolder"; file = new File(folderName); isFileDeleted = file.delete(); if(isFileDeleted) { System.out.println("Empty Folder deleted "); } else { System.out.println("Empty Folder deletion is failed for "+folderName); } } }
Output:
Folder with files is not deleted Empty Folder deleted
Note: if the folder is empty then only folder will be deleted and folder which has files won't be deleted. But, we can delete the files folder after deleting all files.
4. Conclusion
In this article, we've seen how to delete the files and folder in java with examples.
Popular Posts
- 3 Ways to Fix Git Clone "Filename too long" Error in Windows [Fixed]
- Adding/Writing Comments in Java, Comment types with Examples
- Java Program To Reverse A String Without Using String Inbuilt Function reverse()
- Java Thread.join() Examples to Wait for Another Thread
- Java IS-A and HAS-A Relationship With Examples