Thursday, March 4, 2021

How to get value from Map using Key in Java8

 In Java8, using below code can get value from Map using key:

package com.puneet.java8examples;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class GetValueFromMap {

	public static void main(String[] args) {
		
		Map<Integer,String> carMap = new HashMap<>();
		carMap.put(1, "Honda");
		carMap.put(2, "Hundai");
		carMap.put(3, "Renault");
		carMap.put(4, "Yamaha");
		
		//In Java8 - fetch value from map using key
		// Fetch car model basis of key
		Integer key = 2;
		Optional<String> carModel = carMap.entrySet().stream().
				filter(e-> e.getKey()==key).map(Map.Entry::getValue).findFirst();
		
		//without using map function, can directly use findFirst() function
		String carModel2 = carMap.entrySet().stream().
				filter(e-> e.getKey()==key).findFirst().get().getValue();
		
		System.out.println("Car_key:"+key+" Car_Model:"+ carModel2);
		if (carModel.isPresent()) {
                    System.out.println("Car_key:"+key+" Car_Model:"+ carModel.get());
                }
		
		//In Java8 - fetch key from map using value
		// Fetch key basis of car model
		String carName = "Honda";
		Optional<Integer> carKey = carMap.entrySet().stream().
				filter(e-> e.getValue()==carName).map(Map.Entry::getKey).findFirst();
		
		//without using map function, can directly use findFirst() function
		Integer carKey2 = carMap.entrySet().stream().
						filter(e-> e.getValue()==carName).findFirst().get().getKey();
		System.out.println("\nCar_Model:" + carName + " Car_key:"+ carKey2);
		if (carKey.isPresent()) {
                    System.out.println("\nCar_Model:" + carName + " Car_key:"+ carKey.get());
                }
	}

}
Output:
Car_key:2 Car_Model:Hundai

Car_key:2 Car_Model:Hundai

Car_Model:Honda Car_key:1

Car_Model:Honda Car_key:1

How to convert Map to two List in Java8

 Below code can be used for converting Map into two List in Java8 :


package com.puneet.java8examples;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class GetValueFromMapUsingKey {

	public static void main(String[] args) {
		
		Map<Integer,String> carMap = new HashMap<>();
		carMap.put(1, "Honda");
		carMap.put(2, "Hundai");
		carMap.put(3, "Renault");
		carMap.put(4, "Yamaha");
		
		//In Java8 - convert map into two list
		List<String> valueList = new ArrayList();
		
		// Convert Map keys to a List and add values to valueList during processing
		List<Integer> keyList = carMap.entrySet().stream().peek(e->valueList.add(e.getValue())).
				map(e->e.getKey()).collect(Collectors.toList());
		System.out.println("Car keys:");
		keyList.forEach(System.out::println);
		System.out.println("\nCar values:");
		valueList.forEach(System.out::println);
		
	}

}
Output:
Car keys:
1
2
3
4

Car values:
Honda
Hundai
Renault
Yamaha

How to convert Map to List in Java8

 Below is the code snippet that can be used for converting map to list in java8:


package com.puneet.java8examples;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class ConvertMapToList {

	public static void main(String[] args) {
		
		Map<Integer,String> carMap = new HashMap<>();
		carMap.put(1, "Honda");
		carMap.put(2, "Hundai");
		carMap.put(3, "Renault");
		carMap.put(4, "Yamaha");
		
		//Before Java 8
		// Convert Map values to a List
		List<String> valueListBeforeJava8 = new ArrayList(carMap.values());
		System.out.println("Car values:" + valueListBeforeJava8);
		
		// Convert Map keys to a List
		List<Integer> keyListBeforeJava8 = new ArrayList(carMap.keySet());
		System.out.println("\nCar keys:" + keyListBeforeJava8);
		
		//In Java8
		// Convert Map values to a List
		List<String> valueList = carMap.values().stream().collect(Collectors.toList());
		System.out.println("\nCar values:");
		valueList.forEach(System.out::println);
		
		// Convert Map keys to a List
		List<Integer> keyList = carMap.keySet().stream().collect(Collectors.toList());
		System.out.println("\nCar keys:");
		keyList.forEach(System.out::println);
		
	}

}

 Output:

Car values:[Honda, Hundai, Renault, Yamaha]

Car keys:[1, 2, 3, 4]

Car values:
Honda
Hundai
Renault
Yamaha

Car keys:
1
2
3
4

Sunday, February 28, 2021

How to extract long name files from zip



For u

nzip zip files that have more than 260 symbols,

 best solution is 7-Zip. it supports the file pathname more than 260 characters.
As per 7-zip sourceforge thread, it can supports pathnames up to 32,000 characters in length.

More details can be found on their release notes

9.32 alpha     2013-12-01
-------------------------
- Improved support for file pathnames longer than 260 characters.

Saturday, February 27, 2021

Java Interview Questions

What is the difference between java.util.Date and java.sql.Date?
The basic difference is java.util.Date represents both Date and Time information, whereas java.sql.Date represents only Date
java.sql.Date is used only in JDBC to identify SQL DATE value. 
This is the reason we can't map java.util.Date date to util java.sql.Date.

java.sql.Date: this class extends java.util.Date class and as per javadoc, it is just a thin wrapper around millisecond value which is used by JDBC to identify an SQL DATE type. 

check below code snippet:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class DateTimeExample {
	public static void main(String[] args) {
		//java.util.Date
		java.util.Date utilDate = new java.util.Date();
		long dateTimeInMilliSeconds = utilDate.getTime();
		System.out.println("utilDate: " + utilDate);
		System.out.println("dateTimeInMilliSeconds: " + dateTimeInMilliSeconds);
		
		//passing milliseconds to java.sql.Date constructor
		java.sql.Date sqlDate = new java.sql.Date(dateTimeInMilliSeconds);
		System.out.println("sqlDate: " + sqlDate);
	}
}
Output:
utilDate: Sat Feb 27 22:39:36 IST 2021 

dateTimeInMilliSeconds: 1614445776759 

sqlDate: 2021-02-27
Explanation: utilDate variable contains date and time both and when we pass the generated milliseconds to java.sql.Date object then only date is returned.

How to show code snippet in blogs


Generally blogs does not provide the settings to insert code blocks in blogs. Below are the some useful solutions those can be uses for the code block purpose.

1. hilite.me

1. Visit hilite.me and Paste your code in source code window.
2. Select the language.
3. Select if you need to add line numbers to code view.
4. Click on Highlight button
5. Validate the format in preview window.



6. Go to your blog, Convert your blog view to HTML view.
7. Paste the HTML code generated by hilite.
8. Switch back to Compose view to check the result.


1. Visit https://pinetools.com/syntax-highlighter and Paste your code in Highlighted window.
2. Choose "Select the language" or "Auto Detect" option.
3. Select the language if you choose option "Select the language" in step 3.
4. Select the style from drop down.
5. Click on "Highlight!" button.
6. In Highlighted window, code is shown after applying styles.
7. In Highlighted code window, html code is shown that can be used in blog.
pineTool Code Highlighter


How to convert milliseconds to date in java


In java, java.util.Date class has constructor Date(long milliseconds) that provides a Date() class object for the passed milliseconds. The milliseconds are counterd from first moment of 1970 ie January 1, 1970, 00:00:00 GMT.

Below is the the program to convert milliseconds to date in java:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class MillisToDateCoverter {
 
    public static void main(String[] args) {
        long milliSeconds = 1560672963853L; 
   
        //Creates a simple date formatter 
        DateFormat dateFormat = new SimpleDateFormat("dd MMM yyyy HH:mm:ss"); 
        //Create date from milliseconds
        Date date = new Date(milliSeconds); 
        //Parse the date using date formatter
        System.out.println("Date:" + dateFormat.format(date)); 
    } 
}

 

Output:  Date:16 Jun 2019 13:46:03

How to get value from Map using Key in Java8

 In Java8, using below code can get value from Map using key: package com.puneet.java8examples; import java.util.HashMap; import java.u...