javascript Map code example

Example 1: map()

The map() method creates a new array populated with the results of calling 
a provided function on every element in the calling array.

const array1 = [1, 4, 9, 16];

// pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// expected output: Array [2, 8, 18, 32]

Example 2: map

LIST: Can store duplicate values,
      Keeps the insertion order. 
      It allows multiple null values, 
      Also we can read a certain value by index.
- ArrayList not syncronized, array based class 
- LinkedList not synchronized, doubly linked
- Vector is synchronized, thread safe

SET: Can only store unique values, 
     And does not maintain order
- HashSet can have null, order is not guaranteed
- LinkedHashSet can have null and keeps the order 
- TreeSet sorts the order and don't accept null 

QUQUE : Accepts duplicates, 
        Doesn't have index num,
        First in first our order.  
       
MAP : is a (key-value format) 
      and keys are always unique, 
      and value can be duplicated. 
- HashTable don't have null key, sychronized(thread-safe)
- LinkedHashMap can have null key, keeps order
- HasHMap can have null key, order is not guaranteed
- TreeMap doesn't have null key and keys are sorted

Example 3: map

for (let {title, artist} of songs) {
  return title
}

Example 4: Map

Map<String, String> words = new HashMap<>();
words.put("apple", "alma");
words.put("peer", "körte");

System.out.println(words.get("apple")); // alma

words.put("apple", "Apfel"); // Felülírja az értéket
System.out.println(words.get("apple")); // Apfel

Set<String> keys = words.keySet(); // Kulcsok
Collection<String> values = words.values(); // Értékek

for (Map.Entry<String, String> entry: words.entrySet()) {
    System.out.println(entry.getKey() + " - " + entry.getValue());
}

Example 5: go maps

var m map[string]int
m = make(map[string]int)
m["key"] = 42
fmt.Println(m["key"])

delete(m, "key")

elem, ok := m["key"] // test if key "key" is present and retrieve it, if so

// map literal
var m = map[string]Vertex{
    "Bell Labs": {40.68433, -74.39967},
    "Google":    {37.42202, -122.08408},
}

// iterate over map content
for key, value := range m {
}

Tags: