Related
This question already has answers here:
Sort a parallel array using Arrays.sort()
(5 answers)
Closed 4 years ago.
I'm creating a console game in Java. And I want to keep track of the scores and names.
I've already created two arrays.
String[] PlayerNames = {"Bob", "Rick", "Jack"}; // just an example
int[] PlayerScores = {40, 20, 60}; // just an example
I want to sort their scores, but also know who the score belongs to, and then print it out like this:
Jack 60
Bob 40
Rick 20
Create a map with the player names as the keys and the scores as the values, then sort the map based on the values:
public static void main(String[] args) {
Map<String, Integer> unsortedMap = new HashMap<String, Integer>();
unsortedMap.put("Jack", 60);
unsortedMap.put("Bob", 40);
unsortedMap.put("Rick", 20);
Map<String, Integer> sortedMap = sortByValue(unsortedMap);
printMap(sortedMap);
}
private static Map<String, Integer> sortByValue(Map<String, Integer> unsortMap) {
// 1. Convert Map to List of Map
List<Map.Entry<String, Integer>> list =
new LinkedList<Map.Entry<String, Integer>>(unsortMap.entrySet());
// 2. Sort list with Collections.sort(), provide a custom Comparator
// Try switch the o1 o2 position for a different order
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1,
Map.Entry<String, Integer> o2) {
return (o1.getValue()).compareTo(o2.getValue());
}
});
// 3. Loop the sorted list and put it into a new insertion order Map LinkedHashMap
Map<String, Integer> sortedMap = new LinkedHashMap<String, Integer>();
for (Map.Entry<String, Integer> entry : list) {
sortedMap.put(entry.getKey(), entry.getValue());
}
/*
//classic iterator example
for (Iterator<Map.Entry<String, Integer>> it = list.iterator(); it.hasNext(); ) {
Map.Entry<String, Integer> entry = it.next();
sortedMap.put(entry.getKey(), entry.getValue());
}*/
return sortedMap;
}
public static <K, V> void printMap(Map<K, V> map) {
for (Map.Entry<K, V> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey()
+ " Value : " + entry.getValue());
}
}
Note: see https://www.mkyong.com/java/how-to-sort-a-map-in-java/ for more details.
You can use a hashmap for this. Use each name from playerNames as a key and create a list for the values (in case two or more players with the same name get a score). A hashmap allows only one value per key, which is why you should create a list of integers for the scores.
Map<String, List<Integer>> scoreboard = new HashMap<>();
I need create inverse map - select unique values and for them find keys.
Seems that only way is to iterate all key/value pairs, because entrySet returns set of <key,value> so value not unique?
The values in a map may not be unique. But if they are (in your case) you can do as you wrote in your question and create a generic method to convert it:
private static <V, K> Map<V, K> invert(Map<K, V> map) {
Map<V, K> inv = new HashMap<V, K>();
for (Entry<K, V> entry : map.entrySet())
inv.put(entry.getValue(), entry.getKey());
return inv;
}
Java 8:
public static <V, K> Map<V, K> invert(Map<K, V> map) {
return map.entrySet()
.stream()
.collect(Collectors.toMap(Entry::getValue, Entry::getKey));
}
Example of usage:
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Hello", 0);
map.put("World!", 1);
Map<Integer, String> inv = invert(map);
System.out.println(inv); // outputs something like "{0=Hello, 1=World!}"
}
Side note: the put(.., ..) method will return the the "old" value for a key. If it is not null you may throw a new IllegalArgumentException("Map values must be unique") or something like that.
Take a look at Google Guava BiMap.
Example usage
Map<Integer, String> map = new HashMap<>();
map.put(1, "one");
map.put(2, "two");
Map<String, Integer> inverted = HashBiMap.create(map).inverse();
To get an inverted form of a given map in java 8:
public static <K, V> Map<V, K> inverseMap(Map<K, V> sourceMap) {
return sourceMap.entrySet().stream().collect(
Collectors.toMap(Entry::getValue, Entry::getKey,
(a, b) -> a) //if sourceMap has duplicate values, keep only first
);
}
Example usage
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
Map<String, Integer> inverted = inverseMap(map);
Seems that only way is to iterate all key/value pairs, because entrySet returns set of so value not unique?
It's one way at least. Here's an example:
Map<Integer, String> map = new HashMap<Integer, String>();
map.put(1, "one");
map.put(2, "two");
Map<String, Integer> inverted = new HashMap<String, Integer>();
for (Integer i : map.keySet())
inverted.put(map.get(i), i);
In case of non-unique values, this algorithm will map the last value found to it's key. (Since the iteration order is undefined for most maps, this should be as good as any solution.)
If you really do want to keep the first value found for each key, you could change it to
if (!inverted.containsKey(map.get(i)))
inverted.put(map.get(i), i);
I would give another approach to this problem giving an extra dimension:
duplicate values in EntrySet.
public static void main(String[] args) {
HashMap<Integer, String> s = new HashMap<Integer, String>();
s.put(1, "Value1");
s.put(2, "Value2");
s.put(3, "Value2");
s.put(4, "Value1");
/*
* swap goes here
*/
HashMap<String,List<Integer>> newMap = new HashMap<String, List<Integer>>();
for (Map.Entry<Integer, String> en : s.entrySet()) {
System.out.println(en.getKey() + " " + en.getValue());
if(newMap.containsKey(en.getValue())){
newMap.get(en.getValue()).add(en.getKey());
} else {
List<Integer> tmpList = new ArrayList<Integer>();
tmpList.add(en.getKey());
newMap.put(en.getValue(), tmpList);
}
}
for(Map.Entry<String, List<Integer>> entry: newMap.entrySet()){
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
T result will be that:
1 Value1 2 Value2 3 Value2 4 Value1 Value1 [1, 4] Value2 [2, 3]
Apache Commons Collections also provides a BidiMap interface for bi-directional maps, along with several implementations.
BidiMap JavaDoc
If your values duplicate and you need to store keys in list you can go with
val invertedMap = originalMap.entrySet().stream()
.collect(Collectors.groupingBy(
Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.toList()))
);
You have to assume that values may be identical, since the Map contract allows it.
In my opinion the best solution lies in using a wrapper. It will contain the original value, and add an id. Its hashCode() function will rely on the id, and you provide a Getter for the original value.
Code would be something like this:
public class MapKey
{
/**
* A new ID to differentiate equal values
*/
private int _id;
/**
* The original value now used as key
*/
private String _originalValue;
public MapKey(String originalValue)
{
_originalValue = originalValue;
//assuming some method for generating ids...
_id = getNextId();
}
public String getOriginalValue()
{
return _originalValue;
}
#Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + _id;
return result;
}
#Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
MapKey other = (MapKey) obj;
if (_id != other._id)
return false;
return true;
}
#Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("MapKey value is ");
sb.append(_originalValue);
sb.append(" with ID number ");
sb.append(_id);
return sb.toString();
}
Inverting the map would be something like this:
public Map <MapKey, Integer> invertMap(Map <Integer, String> map)
{
Map <MapKey, Integer> invertedMap = new HashMap <MapKey, Integer>();
Iterator<Entry<Integer, String>> it = map.entrySet().iterator();
while(it.hasNext())
{
//getting the old values (to be reversed)
Entry<Integer, String> entry = it.next();
Integer oldKey = entry.getKey();
String oldValue = entry.getValue();
//creating the new MapKey
MapKey newMapKey = new MapKey(oldValue);
invertedMap.put(newMapKey, oldKey);
}
return invertedMap;
}
Printing the values something like this:
for(MapKey key : invertedMap.keySet())
{
System.out.println(key.toString() + " has a new value of " + invertedMap.get(key));
}
None of this code is tested, but I believe it's the best solution since it makes use of OO inheritance design instead of "c" style checks and allows you to display all the original keys and values.
With Guava
Multimaps.transformValues(Multimaps.index(map.entrySet(), Map.Entry::getValue),
Map.Entry::getKey)
You'll get a multimap (basically a map of lists) in return.
I need to sort a 2d key/value pair by the value. I have read many references about this on the web and have ended up writing my own class to do this using HashMaps(see below). I put the code into a condensed working class that reproduces the problem with the minimum amount of code so that you can just cut and paste it into your IDE for quick diagnostics.
As you can see, the method that I wrote is correctly sorting the values before they are entered into sortedMap. However, for some reason, they values are then again unordered in a different way when I try to subsequently iterate through sortedMap.
Can anyone show me how to fix the code below so that I iterate through a resulting 2D data object that gives me my data in descending order?
EDIT: Re-wrote using TreeMaps, and am still getting a similar problem. Here is the re-written code:
import java.util.*;
public class HashMapDemo {
public static void main(String args[]) {
// Code that creates and populates the unordered HashMap:
TreeMap<Integer, Double> unSortedMap = new TreeMap<Integer, Double>();
unSortedMap.put(1343, 0.521851);
unSortedMap.put(1950, -0.301208);
unSortedMap.put(3667, -0.0280762);
unSortedMap.put(3879, 0.154724);
unSortedMap.put(4124, 0.022583);
// Code that calls the ordering method:
TreeMap<Integer, Double> sortedMap = new TreeMap<Integer, Double>(
sortTreeMap(unSortedMap));
// Code that iterates through the "sorted" hashmap.
System.out.println("now iterate through sortedMap: ");
for (Integer key : sortedMap.keySet()) {
System.out.println("key, sortedMap.get(key) are: " + key + ", "
+ sortedMap.get(key));
}
}
// Code for the ordering method. Note that the println tests indicate that
// this method is correctly sorting the key/value pairs in the hashmap:
private static TreeMap<Integer, Double> sortTreeMap(
TreeMap<Integer, Double> input) {
System.out
.println("input.size() upon entering sortHasMap() function is: "
+ input.size());
int startSize = input.size();
// create a hashmap to store sorted output
TreeMap<Integer, Double> sortedMap = new TreeMap<Integer, Double>();
// repeat the following process once for every key/value pair in the
// hashmap
for (int i = 0; i < startSize; i++) {
int mySize = input.size();
System.out.println("mySize is: " + mySize);
double maxVal = Double.NEGATIVE_INFINITY;
int maxKey = 0;
// iterate through each key in hashmap to find key/value of max
// value
for (Integer key : input.keySet()) {
if (maxVal < input.get(key)) {
maxVal = input.get(key);
maxKey = key;
}
}
// add key/value of max of that iteration to sorted map and remove
// from input before next iteration
sortedMap.put(maxKey, maxVal);
input.remove(maxKey);
System.out.println("sortedMap.put(maxKey, maxVal) are: " + maxKey
+ ", " + maxVal);
}
return sortedMap;
}
}
You need only two lines to achieve what you want. Here are those two lines:
Map<Integer, Double> sortedMap = new TreeMap<Integer, Double>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return map.get(o2).compareTo(map.get(o1)); // reverse order of values
}
});
sortedMap.putAll(map);
Here's the complete runnable code:
public static void main(String[] args) {
final Map<Integer, Double> map = new HashMap<Integer, Double>();
map.put(1343, 0.521851);
map.put(1950, -0.301208);
map.put(3667, -0.0280762);
map.put(3879, 0.154724);
map.put(4124, 0.022583);
Map<Integer, Double> sortedMap = sortMap(map);
for (Map.Entry<Integer, Double> entry : sortedMap.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
}
public static Map<Integer, Double> sortMap(final Map<Integer, Double> map) {
Map<Integer, Double> sortedMap = new TreeMap<Integer, Double>(new Comparator<Integer>() {
public int compare(Integer o1, Integer o2) {
return map.get(o2).compareTo(map.get(o1));
}
});
sortedMap.putAll(map);
return sortedMap;
}
Output:
1343, 0.521851
3879, 0.154724
4124, 0.022583
3667, -0.0280762
1950, -0.301208
Notes: You specify how you want entries ordered in a TreeSet by passing the Comparator you want to use into the constructor. The TreeSet implementation does the rest.
Other notes:
The best way to iterate over the keys/values of a map is by iterating over Map.entrySet()
Always use the abstract type for your variables - eg Map<?, ?> myMap not the concrete implementation (ie HashMap<?, ?> myMap)
Here's the generic version of the sortMap method that will sort any suitable map based on the reverse order of the values:
public static <K, V extends Comparable<V>> Map<K, V> sortMap2(final Map<K, V> map) {
Map<K, V> sortedMap = new TreeMap<K, V>(new Comparator<K>() {
public int compare(K o1, K o2) {
return map.get(o2).compareTo(map.get(o1));
}
});
sortedMap.putAll(map);
return sortedMap;
}
Use a TreeMap. Its a SortedMap that uses the natural ordering of keys. In your case, it will order by the Integer key.
It does the sorting for you.
java.util.HashMap is unordered.
This class makes no guarantees as to the order of the map; in
particular, it does not guarantee that the order will remain constant
over time.
EDIT After reading the question correctly
Use a Comparator for the TreeMap constructor that compares the values.
I have this HashMap that I need to print out in ascending order according to the values contained in it (not the keys).
But the order when I print it out is seemingly random.
What's the best way to print it out in ascending value order?
Map<String, String> codes = new HashMap<String, String>();
codes.put("A1", "Aania");
codes.put("X1", "Abatha");
codes.put("C1", "Acathan");
codes.put("S1", "Adreenas");
In other words, the example above should print out as this:
A1, Aania
X1, Abatha
C1, Acathan
S1, Adreenas
You aren't going to be able to do this from the HashMap class alone.
I would take the Map<String, String> codes, construct a reverse map of TreeMap<String, String> reversedMap where you map the values of the codes Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.
Map<String, String> reversedMap = new TreeMap<String, String>(codes);
//then you just access the reversedMap however you like...
for (Map.Entry entry : reversedMap.entrySet()) {
System.out.println(entry.getKey() + ", " + entry.getValue());
}
There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.
You'll need to make a list of the keys, sort them according to the corresponding values, then iterate over the sorted keys.
Map<String, String> map = getMyMap();
List<String> keys = new ArrayList<String>(map.keySet());
Collections.sort(keys, someComparator);
for (String key: keys) {
System.out.println(key + ": " + map.get(key));
}
As for what to use for someComparator, here are some handy, generic Comparator-creating routines I often find useful. The first one sorts by the values according to their natural ordering, and the second allows you to specify any arbitrary Comparator to sort the values:
public static <K, V extends Comparable<? super V>>
Comparator<K> mapValueComparator(final Map<K, V> map) {
return new Comparator<K>() {
public int compare(K key1, K key2) {
return map.get(key1).compareTo(map.get(key2));
}
};
}
public static <K, V>
Comparator<K> mapValueComparator(final Map<K, V> map,
final Comparator<V> comparator) {
return new Comparator<K>() {
public int compare(K key1, K key2) {
return comparator.compare(map.get(key1), map.get(key2));
}
};
}
It's time to add some lambdas:
codes.entrySet()
.stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.forEach(System.out::println);
the for loop of for(Map.Entry entry: codes.entrySet()) didn't work for me. Used Iterator instead.
Iterator<Map.Entry<String, String>> i = codes.entrySet().iterator();
while(i.hasNext()){
String key = i.next().getKey();
System.out.println(key+", "+codes.get(key));
}
you just need to use:
Map<>.toString().replace("]","\n");
and replaces the ending square bracket of each key=value set with a new line.
Java 8
map.entrySet().stream().sorted(Map.Entry.comparingByValue()).forEach(System.out::println);
Create a TreeMap<String,String>
Add each of the HashMap entries with the value as the key.
iterate the TreeMap
If the values are nonunique, you would need a list in the second position.
You can use a list of the entry set rather than the key set and it is a more natural choice given you are sorting based on the value. This avoids a lot of unneeded lookups in the sorting and printing of the entries.
Map<String, String> map = ...
List<Map.Entry<String, String>> listOfEntries = new ArrayList<Map.Entry<String, String>>(map.entrySet());
Collections.sort(listOfEntries, new SortByValueComparator());
for(Map.Entry<String, String> entry: listOfEntries)
System.out.println(entry);
static class SortByValueComparator implements Comparator<Map.Entry<String, String>> {
public int compareTo(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
return e1.getValue().compateTo(e2.getValue());
}
}
the simplest and shortest code i think is this:
public void listPrinter(LinkedHashMap<String, String> caseList) {
for(Entry entry:caseList.entrySet()) {
System.out.println("K: \t"+entry.getKey()+", V: \t"+entry.getValue());
}
}
The simplest solution would be to use a sorted map like TreeMap instead of HashMap.
If you do not have control over the map construction, then the minimal solution would be to construct a sorted set of keys. You don't really need a new map.
Set<String> sortedKeys = new TreeSet<String>();
sortedKeys.addAll(codes.keySet());
for(String key: sortedKeys){
println(key + ":" + codes.get(key));
}
Try:
try
{
int cnt= m.getSmartPhoneCount("HTC",true);
System.out.println("total count of HTC="+cnt);
}
catch (NoSuchBrandSmartPhoneAvailableException e)
{
// TODO Auto-generated catch
e.printStackTrace();
}
SmartPhone[] sp=new SmartPhone[4];
sp[0]=new SmartPhone(1,"HTC","desire","black",20000,10,true,true);
sp[1]=new SmartPhone(2,"samsung","grand","black",5000,10,false,true);
sp[2]=new SmartPhone(14,"google nexus","desire","black",2000,30,true,false);
sp[3]=new SmartPhone(13,"HTC","desire","white",50000,40,false,false);
while (itr.hasNext()) {
Vehicle vc=(Vehicle) itr.next();
if(vc.getVehicleType().equalsIgnoreCase(s)) {
count++;
}
}
How to move a particular HashMap entry to Last position?
For Example, I have HashMap values like this:
HashMap<String,Integer> map = new HashMap<String,Integer>();
map= {Not-Specified 1, test 2, testtest 3};
"Not-Specified" may come in any position. it may come first or in the middle of the map. But i want to move the "Not-Specified" to the last position.
How can I do that?
To answer your question in one sentence:
Per default, Maps don't have a last entry, it's not part of their contract.
And a side note: it's good practice to code against interfaces, not the implementation classes (see Effective Java by Joshua Bloch, Chapter 8, Item 52: Refer to objects by their interfaces).
So your declaration should read:
Map<String,Integer> map = new HashMap<String,Integer>();
(All maps share a common contract, so the client need not know what kind of map it is, unless he specifies a sub interface with an extended contract).
Possible Solutions
Sorted Maps:
There is a sub interface SortedMap that extends the map interface with order-based lookup methods and it has a sub interface NavigableMap that extends it even further. The standard implementation of this interface, TreeMap, allows you to sort entries either by natural ordering (if they implement the Comparable interface) or by a supplied Comparator.
You can access the last entry through the lastEntry method:
NavigableMap<String,Integer> map = new TreeMap<String, Integer>();
// add some entries
Entry<String, Integer> lastEntry = map.lastEntry();
Linked maps:
There is also the special case of LinkedHashMap, a HashMap implementation that stores the order in which keys are inserted. There is however no interface to back up this functionality, nor is there a direct way to access the last key. You can only do it through tricks such as using a List in between:
Map<String,String> map = new LinkedHashMap<String, Integer>();
// add some entries
List<Entry<String,Integer>> entryList =
new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
Entry<String, Integer> lastEntry =
entryList.get(entryList.size()-1);
Proper Solution:
Since you don't control the insertion order, you should go with the NavigableMap interface, i.e. you would write a comparator that positions the Not-Specified entry last.
Here is an example:
final NavigableMap<String,Integer> map =
new TreeMap<String, Integer>(new Comparator<String>() {
public int compare(final String o1, final String o2) {
int result;
if("Not-Specified".equals(o1)) {
result=1;
} else if("Not-Specified".equals(o2)) {
result=-1;
} else {
result =o1.compareTo(o2);
}
return result;
}
});
map.put("test", Integer.valueOf(2));
map.put("Not-Specified", Integer.valueOf(1));
map.put("testtest", Integer.valueOf(3));
final Entry<String, Integer> lastEntry = map.lastEntry();
System.out.println("Last key: "+lastEntry.getKey()
+ ", last value: "+lastEntry.getValue());
Output:
Last key: Not-Specified, last value: 1
Solution using HashMap:
If you must rely on HashMaps, there is still a solution, using a) a modified version of the above comparator, b) a List initialized with the Map's entrySet and c) the Collections.sort() helper method:
final Map<String, Integer> map = new HashMap<String, Integer>();
map.put("test", Integer.valueOf(2));
map.put("Not-Specified", Integer.valueOf(1));
map.put("testtest", Integer.valueOf(3));
final List<Entry<String, Integer>> entries =
new ArrayList<Entry<String, Integer>>(map.entrySet());
Collections.sort(entries, new Comparator<Entry<String, Integer>>(){
public int compareKeys(final String o1, final String o2){
int result;
if("Not-Specified".equals(o1)){
result = 1;
} else if("Not-Specified".equals(o2)){
result = -1;
} else{
result = o1.compareTo(o2);
}
return result;
}
#Override
public int compare(final Entry<String, Integer> o1,
final Entry<String, Integer> o2){
return this.compareKeys(o1.getKey(), o2.getKey());
}
});
final Entry<String, Integer> lastEntry =
entries.get(entries.size() - 1);
System.out.println("Last key: " + lastEntry.getKey() + ", last value: "
+ lastEntry.getValue());
}
Output:
Last key: Not-Specified, last value: 1
HashMap doesn't have "the last position", as it is not sorted.
You may use other Map which implements java.util.SortedMap, most popular one is TreeMap.
A SortedMap is the logical/best choice, however another option is to use a LinkedHashMap which maintains two order modes, most-recently-added goes last, and most-recently-accessed goes last. See the Javadocs for more details.
When using numbers as the key, I suppose you could also try this:
Map<Long, String> map = new HashMap<>();
map.put(4L, "The First");
map.put(6L, "The Second");
map.put(11L, "The Last");
long lastKey = 0;
//you entered Map<Long, String> entry
for (Map.Entry<Long, String> entry : map.entrySet()) {
lastKey = entry.getKey();
}
System.out.println(lastKey); // 11
move does not make sense for a hashmap since its a dictionary with a hashcode for bucketing based on key and then a linked list for colliding hashcodes resolved via equals.
Use a TreeMap for sorted maps and then pass in a custom comparator.
In such scenario last used key is usually known so it can be used for accessing last value (inserted with the one):
class PostIndexData {
String _office_name;
Boolean _isGov;
public PostIndexData(String name, Boolean gov) {
_office_name = name;
_isGov = gov;
}
}
//-----------------------
class KgpData {
String _postIndex;
PostIndexData _postIndexData;
public KgpData(String postIndex, PostIndexData postIndexData) {
_postIndex = postIndex;
_postIndexData = postIndexData;;
}
}
public class Office2ASMPro {
private HashMap<String,PostIndexData> _postIndexMap = new HashMap<>();
private HashMap<String,KgpData> _kgpMap = new HashMap<>();
...
private void addOffice(String kgp, String postIndex, String officeName, Boolean gov) {
if (_postIndexMap.get(postIndex) == null) {
_postIndexMap.put(postIndex, new PostIndexData(officeName, gov));
}
_kgpMap.put( kgp, new KgpData(postIndex, _postIndexMap.get(postIndex)) );
}
Find missing all elements from array
int[] array = {3,5,7,8,2,1,32,5,7,9,30,5};
TreeMap<Integer, Integer> map = new TreeMap<>();
for(int i=0;i<array.length;i++) {
map.put(array[i], 1);
}
int maxSize = map.lastKey();
for(int j=0;j<maxSize;j++) {
if(null == map.get(j))
System.out.println("Missing `enter code here`No:"+j);
}