Accessing the last entry in a Map
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
Getting value of last Hashmap key
You can't use a normal HashMap for that, you need another member of the "collections" family; in thise case, its cousin LinkedHashMap. That one keeps the order in which elements were added. Keep in mind that those two different maps do show different behavior regarding "cost" of insert/delete/iterating operations.
Javascript Map Array Last Item
Try something like:
row.map((rank, i, row) => {
if (i + 1 === row.length) {
// Last one.
} else {
// Not last one.
}
})
Old answer:
const rowLen = row.length;
row.map((rank, i) => {
if (rowLen === i + 1) {
// last one
} else {
// not last one
}
})
Accessing last element of map using map.end()
The iterators are pointing to the same key
No they do not. m.end()--;
is post decrement. Its semantic is to decrement the return value of m.end()
as a side-effect, but return the original value unchanged. So it1 == m.end()
and you get undefined behavior by dereferencing it.
It compiles successfully due to an unfortunate side-effect of operator++
being a member function of a user defined type (the iterator). You can call it even on an r-value like m.end()
, while the built-in post-decrement expects an l-value.
So even though iterators model pointers, they aren't quite the same. To contrast, this program:
char* foo();
int main() {
foo()--;
}
will produce an error on foo()--
, because foo()
is an r-value pointer, and we cannot decrement it.
How to get last item in map function in React
Test the index against the length of the array.
const array = ['a', 'b', 'c', 'd'];
const mapped = array.map(
(value, index, array) => {
if (array.length - 1 === index) {
console.log(`${value} is the last item in the array`);
return `-->${value.toUpperCase()}<--`;
} else {
return value.toLowerCase();
}
}
);
console.log({mapped});
How to return last added value from the HashMap
There is no direct way to do what you want. Map
is an unordered construct. However, there are some options:
- Keep a reference to the last item added somewhere
- Create your own key type that includes information about when the key was added. This would require looping over the key set to see which key was added after some time/value.
- Since you are using integers as a key, without knowing anything else, you could add items by using an incremented variable. Then you're back to the same situation as with the second bullet point.
Related Topics
How I Save and Retrieve an Image on My Server in a Java Webapp
How to Read a File from a Certain Offset in Java
Is Memory Leak? Why Java.Lang.Ref.Finalizer Eat So Much Memory
Integer Arithmetic in Java with Char and Integer Literal
Pass a Local File in to Url in Java
Java Simpledateformat Timezone Offset with Minute Separated by Colon
How to Format Localdate to String
Jaxb Marshalling Unmarshalling with Cdata
How to Check the Bitness of My Os Using Java? (J2Se, Not Os.Arch)
Garbage Collection on a Local Variable
Filter Java Stream to 1 and Only 1 Element
Hash String via Sha-256 in Java
How to Get a Unicode Character's Code
How to Sort Arraylist<Long> in Decreasing Order
How to Check for a Valid Url in Java