PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label hashmap. Show all posts
Showing posts with label hashmap. Show all posts

Saturday, November 12, 2022

[FIXED] why memcached instead of hashmap

 November 12, 2022     hashmap, memcached     No comments   

Issue

I am trying to understand what would be the need to go with a solution like memcached. It may seem like a silly question - but what does it bring to the table if all I need is to cache objects? Won't a simple hashmap do ?


Solution

Quoting from the memcache web site, memcache is…

Free & open source, high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

Memcached is an in-memory key-value store for small chunks of arbitrary data (strings, objects) from results of database calls, API calls, or page rendering. Memcached is simple yet powerful. Its simple design promotes quick deployment, ease of development, and solves many problems facing large data caches. Its API is available for most popular languages.

At heart it is a simple Key/Value store

A key word here is distributed. In general, quoting from the memcache site again,

Memcached servers are generally unaware of each other. There is no crosstalk, no syncronization, no broadcasting. The lack of interconnections means adding more servers will usually add more capacity as you expect. There might be exceptions to this rule, but they are exceptions and carefully regarded.

I would highly recommend reading the detailed description of memcache.



Answered By - Jordan Dea-Mattson
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, November 3, 2022

[FIXED] How to refactor if statements with a Map using Java 8 Lambdas

 November 03, 2022     dictionary, hashmap, java, lambda, validation     No comments   

Issue

I would like to know how i can refactor my code using a Map Data Structure and Lambdas.

Here is my method:

private void validateUserFields(User user) {
    if(user.getName() == null){
        throw new RuntimeException("The user's name cannot be null");
    }
    if(user.getLastName() == null){
        throw new RuntimeException("The user's lastName cannot be null");
    }
    if(user.getDni() == null){
        throw new RuntimeException("The user's dni cannot be null");
    }
    if(user.getVehicle() == null){
        throw new RuntimeException("The user's vehicle cannot be null");
    }
}

I expect a elegant an a simple way to refactor my code.


Solution

Try a map of validations:

private static Map<String, Function<User, ?>> VALIDATIONS = Map.of(
        "name", User::getName,
        "lastName", User::getLastName,
        "dni", User::getDni,
        "vehicle", User::getVehicle
);

private void validateUserFields(User user) {
    VALIDATIONS.entrySet().stream()
        .filter(entry -> entry.getValue().apply(user) == null)
        .map(Map.Entry::getKey)
        .map(field -> String.format("The user's %s cannot be null", field))
        .map(RuntimeException::new)
        .findFirst()
        .ifPresent(e -> {
            throw e;
        });
}

or this briefer version that bypasses the use of method references:

private void validateUserFields(User user) {
    VALIDATIONS.entrySet().stream()
        .filter(entry -> entry.getValue().apply(user) == null)
        .findFirst()
        .ifPresent(e -> {throw new RuntimeException("The user's " + e.getKey() + " cannot be null");});
}

I don't know if it's "elegant", but it is scaleable and flexible.



Answered By - Bohemian
Answer Checked By - Mary Flores (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 1, 2022

[FIXED] What is the time complexity of HashMap.containsKey() in java?

 November 01, 2022     hashmap, java, performance, time-complexity     No comments   

Issue

I need to know: What is the time complexity of HashMap.containsKey() in java?


Solution

From the API doc ofHashMap:

This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets.

Since containsKey() is just a get() that throws away the retrieved value, it's O(1) (assuming the hash function works properly, again).



Answered By - Michael Borgwardt
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, October 26, 2022

[FIXED] Why is the map displaying same value for all entries?

 October 26, 2022     arraylist, hashmap, java, oop     No comments   

Issue

I've recently been learning Java. So basically I created a Student Model class which consists of student's info along with their marks info. And then I created a Student Main Class where I created an object of type Student Model Class. I wanted to create a map of type Map<StudentModelClass,ArrayList<Integer>.

I want to store student details as a key and only their marks which is a list as value in a map. I wrote the code but I don't know why is my map taking all the values in map entries the same marks.

This is my Student Model Class

package com.src.StudentDetailsAsMap;

public class StudentDetails {

    private int stdid;
    private String name;
    private int age;
    private String mobileNumber; 
    private int m1,m2,m3;
    private int total_marks_secured=0;
    private double avg_marks_secured=0.0;

    
    
    public StudentDetails(int stdid, String name, int age, String mobileNumber, int m1, int m2, int m3) {
        this.setStdid(stdid);
        this.setName(name);
        this.setAge(age);
        this.setMobileNumber(mobileNumber);
        this.setM1(m1);
        this.setM2(m2);
        this.setM3(m3);
        this.setTotal_marks_secured(m1+m2+m3);
        this.setAvg_marks_secured(this.getTotal_marks_secured()/3);
    }
    public StudentDetails() {
    }
    public int getStdid() {
        return stdid;
    }
    public void setStdid(int stdid) {
        this.stdid = stdid;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getMobileNumber() {
        return mobileNumber;
    }
    public void setMobileNumber(String mobileNumber) {
        this.mobileNumber = mobileNumber;
    }
    public int getM1() {
        return this.m1;
    }
    public void setM1(int m1) {
        this.m1 = m1;
    }
    public int getM2() {
        return this.m2;
    }
    public void setM2(int m2) {
        this.m2 = m2;
    }
    public int getM3() {
        return this.m3;
    }
    public void setM3(int m3) {
        this.m3 = m3;
    }
    public int getTotal_marks_secured() {
        return total_marks_secured;
    }
    public void setTotal_marks_secured(int total_marks_secured) {
        this.total_marks_secured = total_marks_secured;
    }
    public double getAvg_marks_secured() {
        return avg_marks_secured;
    }
    public void setAvg_marks_secured(double avg_marks_secured) {
        this.avg_marks_secured = avg_marks_secured;
    }
    
    
    public void display() {
        System.out.println("Student [stdid=" + stdid + ", name=" + name + ", age=" + age + ", mobileNumber=" + mobileNumber
                + ", m1=" + m1 + ", m2=" + m2 + ", m3=" + m3 + ", total_marks_secured=" + total_marks_secured
                + ", avg_marks_secured=" + avg_marks_secured + "]");
    }
    
}

This is my Student Main Class

 package com.src.StudentDetailsAsMap;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

public class StudentMap {
    public static void main(String[] arg) {
        StudentDetails obj = new StudentDetails();
        ArrayList<Integer> marks = new ArrayList<Integer>();
        Map<StudentDetails,ArrayList<Integer>> mp = new HashMap<StudentDetails,ArrayList<Integer>>();
        
        obj = new StudentDetails(1,"kevin",20,"23425",89,98,89);
        marks.add(obj.getM1());
        marks.add(obj.getM2());
        marks.add(obj.getM3());
        System.out.println("marks1: " + marks.get(0) + " " + marks.get(1) +" " + marks.get(2));
        mp.put(obj,marks);
        
        marks.clear();
        obj = new StudentDetails(2,"fred",20,"12345",81,98,89);
        marks.add(obj.getM1());
        marks.add(obj.getM2());
        marks.add(obj.getM3());
        System.out.println("marks2 " + marks.get(0) + " " + marks.get(1) +" " + marks.get(2));
        mp.put(obj,marks);
        
        obj = new StudentDetails(3,"rue",20,"24564",89,56,89);
        marks.clear();
        marks.add(obj.getM1());
        marks.add(obj.getM2());
        marks.add(obj.getM3());
        mp.put(obj,marks);
        
        
        obj = new StudentDetails(4,"paxton",20,"85756",89,35,89);
        marks.clear();
        marks.add(obj.getM1());
        marks.add(obj.getM2());
        marks.add(obj.getM3());
        mp.put(obj,marks);
        
        
        for(Entry mp1 : mp.entrySet()) {
            StudentDetails s = (StudentDetails) mp1.getKey();
            System.out.println("Key: ");
            s.display();
            System.out.println("Value: ");
            ArrayList<Integer> arr = (ArrayList<Integer>)mp1.getValue();
            System.out.println(arr);
        }
        
        
    }
    
}

This is the output I got


Solution

The reason is because your array list is the same object from beginning to end.

The ArrayList that your Map<StudentDetails,ArrayList> mp stores are all pointing to same object's memory address, therefore, you will always have same value being print out from your output.

Like @nanofarad said, construct a new ones like you did to StudentDetails obj



Answered By - Gary Liao
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, September 20, 2022

[FIXED] How to iterate through a HashMap<Vec<u8>,Vec<u8>>

 September 20, 2022     hashmap, rust, serialization, slice, vec     No comments   

Issue

As the title says I am trying to iterate through a HashMap of 2 vectors. my code is as follows:

pub fn serialize_hashmap(data: &HashMap<Vec<u8>, Vec<u8>>) -> Result<Vec<u8>, String> {
    let mut serialized_data = Vec::new();
    for (hash, password_data) in &data {
        serialized_data.extend_from_slice(&hash);
        let password_data_length: u64 = password_data.len().try_into().unwrap();
        serialized_data.write_u64::<NativeEndian>(password_data_length).unwrap(); // TODO add error handling
        serialized_data.extend_from_slice(&password_data);
    }

    return Ok(serialized_data);
}

But when I run this code I get the following error:

error[E0277]: the size for values of type `[_]` cannot be known at compilation time
 --> src/main.rs:8:10
  |
8 |     for (hash, password_data) in &data {
  |          ^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `Sized` is not implemented for `[_]`
  = note: all local variables must have a statically known size
  = help: unsized locals are gated as an unstable feature

error[E0277]: the size for values of type `[_]` cannot be known at compilation time
 --> src/main.rs:8:34
  |
8 |     for (hash, password_data) in &data {
  |                                  ^^^^^ doesn't have a size known at compile-time
  |
  = help: the trait `Sized` is not implemented for `[_]`
  = note: only the last element of a tuple may have a dynamically sized type

It seems the issue is that my hashmap is dynamically allocated and its size is not known at runtime. Is there any way to iterate through the HashMap even though it is dynamically allocated? How would something like this normally be done in rust?


Solution

I'm pretty sure your problem is simply that data is already a reference, so when you try to iterate over &data you're iterating over a &&HashMap, which is not iterable. If you remove the ampersand so that it's for ... in data I think the loop should work because then it is just iterating over a &HashMap, which is perfectly fine.



Answered By - BallpointBen
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I copy a hash in Ruby?

 September 20, 2022     copy, deep-copy, hashmap, ruby, serialization     No comments   

Issue

I'll admit that I'm a bit of a ruby newbie (writing rake scripts, now). In most languages, copy constructors are easy to find. Half an hour of searching didn't find it in ruby. I want to create a copy of the hash so that I can modify it without affecting the original instance.

Some expected methods that don't work as intended:

h0 = {  "John"=>"Adams","Thomas"=>"Jefferson","Johny"=>"Appleseed"}
h1=Hash.new(h0)
h2=h1.to_hash

In the meantime, I've resorted to this inelegant workaround

def copyhash(inputhash)
  h = Hash.new
  inputhash.each do |pair|
    h.store(pair[0], pair[1])
  end
  return h
end

Solution

The clone method is Ruby's standard, built-in way to do a shallow-copy:

h0 = {"John" => "Adams", "Thomas" => "Jefferson"}
# => {"John"=>"Adams", "Thomas"=>"Jefferson"}
h1 = h0.clone
# => {"John"=>"Adams", "Thomas"=>"Jefferson"}
h1["John"] = "Smith"
# => "Smith"
h1
# => {"John"=>"Smith", "Thomas"=>"Jefferson"}
h0
# => {"John"=>"Adams", "Thomas"=>"Jefferson"}

Note that the behavior may be overridden:

This method may have class-specific behavior. If so, that behavior will be documented under the #initialize_copy method of the class.



Answered By - Mark Rushakoff
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to extract the value with the key field in hashmap

 September 20, 2022     dto, hashmap, java, key     No comments   

Issue

Map<string,DTO> DTOmap

The hash map has string as the key and the DTO as the value field in a hashmap I am trying to get the DTO values printed in an excel sheet.
Can I use

Set<string> rows=DTOmap.keyset();
For(string key:rows)
Object[] objArr =DTOmap. Get(key);
For (Object obj:objArr){
Cell cell=row.createCell(cellnum++);

Can I use the above method to get all the DTO values using the key field to extract it?


Solution

for(string key:rows){
 Object[] objArr =DTOmap.get(key);
}

This is invalid. Your map is Map<string,DTO> , by calling .get(key) you will get a single DTO instance not an array of it. You need to store all the DTO instances in an array / List for all keys. Something like this :

List<DTO> list = new ArrayList<>();
for(String key:rows){
 DTO dto = DTOmap.get(key);
 list.add(dto);
}

After that you can do whatever you want iterating the list.

for(DTO dto : list){
 //your code 
}

EDIT: As mentioned by @f1sh in the comments .You can do the same just by iterating the map.keyset()

for(String key : DTOmap.keyset()){
 DTO dto = DTOmap.get(key);

 //your code
 Cell cell=row.createCell(cellnum++);
}

It is pointless to use two for-loop to perform some operation which can be done in one.



Answered By - Sayan Bhattacharya
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can i sort HashMap<String,Int> order by their values in Kotlin?

 September 20, 2022     hashmap, kotlin, list, sorting, treemap     No comments   

Issue

Here is my example, how can i do that in Kotlin?

var hashMapForTry = HashMap<String,Int>()

hashMapForTry.put("Hi",5)
hashMapForTry.put("What",7)
hashMapForTry.put("How",2)
hashMapForTry.put("Go",1)
hashMapForTry.put("Ford",9)

Solution

You cannot sort a HashMap because it doesn't guarantee that its entries will be iterated in any particular order. You can, however, arrange the items into a LinkedHashMap which keeps the insertion order:

    val resultMap = hashMapForTry.entries.sortedBy { it.value }.associate { it.toPair() }

    println(resultMap)

Here the entries of hashMapForTry are sorted by entry value, then associate function converts the list of entries into a map that preserves the order of entries from that list.

The result type of this function is Map<String, Int>. If you need to mutate the result further, you can use associateTo function and specify an empty destination LinkedHashMap as a parameter:

....associateTo(LinkedHashMap()) { ... }


Answered By - Ilya
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to update keys of map in dart

 September 20, 2022     algorithm, async-await, dart, flutter, hashmap     No comments   

Issue

I have a simple map "objects" lets assume this :

{
ServoP180V1: {X: 100.0, Y: 0.0}, 
ServoP180V3: {X: 100.0, Y: 0.0}
ServoP180V5: {X: 100.0, Y: 0.0}
}

How I can sort the keys in such way that they will be in an order, like this:

{
ServoP180V1: {X: 100.0, Y: 0.0}, 
ServoP180V2: {X: 100.0, Y: 0.0}
ServoP180V3: {X: 100.0, Y: 0.0}
}

I tried this code but it has problems with returning null sometimes, not sure Im in right way

  sortObjects() {
    int i = 1;
    for (var key in objects.keys) {
      objects.update(
        key.substring(0, key.length - 1) + i.toString(),
        null,
      );
      i++;
    }
  }
The method 'call' was called on null.
Receiver: null
Tried calling: call()

also this way

  sortObjects() {
    int i = 1;
    objects.forEach((key, value) {
      objects.update(
        key.substring(0, key.length - 1) + i.toString(),
        (existingValue) => value,
        ifAbsent: () => value,
      );
      i++;
    });
  }

giving such an error

Exception: Concurrent modification during iteration: 

Thank you in advance !


Solution

So you are changing the key during the foearch loop, this is illegal. I would change the keys by generating another map and then replacing the old one. It is an answer.

Map.update()

Update method of the map only updates the content of the key and only if it exists, but does not change the key itself. I didn't find anything related to changing keys for maps at runtime.

Map<String, dynamic> oldMap = {
  "ServoP180V1": {"X": 100.0, "Y": 0.0},
  "ServoP180V3": {"X": 100.0, "Y": 0.0},
  "ServoP180V5": {"X": 100.0, "Y": 0.0}
};
Map<String, dynamic> newMap = {};
int i = 1;
oldMap.keys.toList().forEach((key) {
  newMap.addAll({
    "${key.substring(0, key.length - 1)}$i":
        oldMap[key]
  });
  i++;
});
print(oldMap);
print(newMap);

result:

{ServoP180V1: {X: 100.0, Y: 0.0}, ServoP180V3: {X: 100.0, Y: 0.0}, ServoP180V5: {X: 100.0, Y: 0.0}}
{ServoP180V1: {X: 100.0, Y: 0.0}, ServoP180V2: {X: 100.0, Y: 0.0}, ServoP180V3: {X: 100.0, Y: 0.0}}


Answered By - Chance
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to fix this suspicious call to hashmap.get

 September 20, 2022     hashmap, java     No comments   

Issue

So this is my HashMap

HashMap<Literal, Double> literalHashMap = new HashMap<>();
for(Literal literal : literalHashSet) {
    if(literal.isTrue(node.state)){ literalHashMap.put(literal, 0.0);}
    else{literalHashMap.put(literal, Double.MAX_VALUE);}
}

Then I do this:

literalHashMap.put((Literal)proposition, updatedCost);

But when I do this:

cost += literalHashMap.get(proposition)

I see a warning saying "suspicious call to hashmap.get".

Any idea how to fix that?


Solution

It's saying suspicious call because you pass a Literal Object as the key (literalHashMap.put((Literal)proposition, updatedCost); you downcast proposition so it becomes a Literal object). So, I can assume that proposition is not a Literal object. However, you pass proposition as the key to the HashMap, which is a different kind of object entirely. To fix this: cost += literalHashMap.get((Literal) proposition);. Or, to save a tiny bit of time:

Literal lit = (Literal) proposition;
literalHashMap.put((lit, updatedCost);
cost += literalHashMap.get(list);

To avoid downcasting twice.



Answered By - Higigig
Answer Checked By - Willingham (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I collect the values of a HashMap into a vector?

 September 20, 2022     hashmap, rust     No comments   

Issue

I can not find a way to collect the values of a HashMap into a Vec in the documentation. I have score_table: HashMap<Id, Score> and I want to get all the Scores into all_scores: Vec<Score>.

I was tempted to use the values method (all_scores = score_table.values()), but it does not work since values is not a Vec.

I know that Values implements the ExactSizeIterator trait, but I do not know how to collect all values of an iterator into a vector without manually writing a for loop and pushing the values in the vector one after one.

I also tried to use std::iter::FromIterator; but ended with something like:

all_scores = Vec::from_iter(score_table.values());
expected type `std::vec::Vec<Score>`
   found type `std::vec::Vec<&Score>`

Thanks to Hash map macro refuses to type-check, failing with a misleading (and seemingly buggy) error message?, I changed it to:

all_scores = Vec::from_iter(score_table.values().cloned());

and it does not produce errors to cargo check.

Is this a good way to do it?


Solution

The method Iterator.collect is designed for this specific task. You're right in that you need .cloned() if you want a vector of actual values instead of references (unless the stored type implements Copy, like primitives), so the code looks like this:

all_scores = score_table.values().cloned().collect();

Internally, collect() just uses FromIterator, but it also infers the type of the output. Sometimes there isn't enough information to infer the type, so you may need to explicitly specify the type you want, like so:

all_scores = score_table.values().cloned().collect::<Vec<Score>>();


Answered By - apetranzilla
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to preserve order of insertion in Map.of factory?

 September 20, 2022     factory-method, hashmap, java, java-9     No comments   

Issue

Java 9 offers Map.of() feature to easily create a map with fixed values.

Problem: I want to create a map that preserves order of insertion like LinkedHashMap. Is that possible with that factory? At least map.of() does not preserv the order...


Solution

There isn't a factory method like LinkedHashMap::of indeed, and a Map does not have an order per-se, so the only way I see it is to build a LinkedHashMap if you really needed one.

Btw from the JEP itself:

Static factory methods on concrete collection classes (e.g., ArrayList, HashSet) have been removed from this proposal ...

There is another wrinkle, which is that static methods on classes are inherited by subclasses. Suppose a static factory method HashMap.of() were to be added. Since LinkedHashMap is a subclass of HashMap, it would be possible for application code to call LinkedHashMap.of(). This would end up calling HashMap.of(), not at all what one would expect!

Point here is that static methods are inherited, but not overridable, thus if such a method would have been added to HashMap it could have not been overridden in LinkedHashMap.

If you can use guava, you could use ImmutableMap that is documented as:

An immutable, hash-based Map with reliable user-specified iteration order...



Answered By - Eugene
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to insert in a nested hashmap?

 September 20, 2022     dictionary, hashmap, java, nested     No comments   

Issue

I have a nested hashmap like

HashMap<String,HashMap<String,Obzect>> map1= new HashMap<>();

The first map key will be object.getId and key of second map can be "p1","p2" or such based on some conditions. I am trying to insert into a hashmap without creating an instance for second map.

map1.put(object.getId,map1.get(object.getId).put("p1",object));

I am getting error message

Required Type: hashmap
Provided Type: object

How to correct this?


Solution

Try this.

public static void main(String[] args) {
    record Obzect(String getId) {}
    Obzect object = new Obzect("id");

    HashMap<String, HashMap<String, Obzect>> map1= new HashMap<>();
    map1.computeIfAbsent(object.getId, k -> new HashMap<>()).put("p1", object);

    System.out.println(map1);
}

output:

{id={p1=Obzect[getId=id]}}


Answered By - 英語は苦手
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to get unique properties from object <Map>

 September 20, 2022     arrays, hashmap, javascript, object, typescript     No comments   

Issue

I have a and Map with one Object that contains a list of arrays. For example:

Map(1) {'SAMSUNG' => Array(5)}
  [[Entries]]
    0: {"SAMSUNG" => Array(5)}
      key: "SAMSUNG"
      value: Array(5)
        0: {externalKey: '0001', brand: 'V', country: 'DE', deviceType: 'TSU4'}
        1: {externalKey: '0002', brand: 'V', country: 'FR', deviceType: 'TSU1'}
        2: {externalKey: '0005', brand: 'N', country: 'DE', deviceType: 'TSU4'}
        3: {externalKey: '0008', brand: 'V', country: 'AB', deviceType: 'TCU4'}
        4: {externalKey: '0009', brand: 'G', country: 'DE', deviceType: 'TCU7'}
        length: 5
        [[Prototype]]: Array(0)
        size: 1
        [[Prototype]]: Map

I like to know how I can get the unique brand country and devicetype , eg: brand['V','N','G'].

First I need to know how to access this map value Array of 5 values.

I tried something like this:

Object.keys(myObj)

But it gives me 'undefined'


Solution

Your map has one key "SAMSUNG", and you can get its contents with mymap.get("SAMSUNG"). That will be an array in this case.

Here is an example on how that map could have been built, how you can get access to the array, and how you could group countries by brand (just as example):

// Create the map (you already have it -- so you wouldn't do this)
const map = new Map().set("SAMSUNG", [
    {externalKey: '0001', brand: 'V', country: 'DE', deviceType: 'TSU4'},
    {externalKey: '0002', brand: 'V', country: 'FR', deviceType: 'TSU1'},
    {externalKey: '0005', brand: 'N', country: 'DE', deviceType: 'TSU4'},
    {externalKey: '0008', brand: 'V', country: 'AB', deviceType: 'TCU4'}, 
    {externalKey: '0009', brand: 'G', country: 'DE', deviceType: 'TCU7'}
]);

// Get access to the array
const arr = map.get("SAMSUNG");

// Example: group countries by brand
const groups = {};
for (const {brand, country} of arr) (groups[brand] ??= []).push(country);
console.log(groups);



Answered By - trincot
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What type of Map should I use if the data does not change?

 September 20, 2022     hashmap, java     No comments   

Issue

I have data that I want to lookup by key.

My particular use case is that the data (key/value and number of elements) does not change once the map is initialised. All key/value values are known at once.

I have generally use a HashMap for this with default constructor (default initial capacity and load factor).

What is the best way build this Map? If I was to use HashMap, what should the default initial capacity and load factor be set to? Is Map.copyOf() a better solution? Does the size of the map matter (20 elements vs 140,000)?

This article https://docs.oracle.com/en/java/javase/15/core/creating-immutable-lists-sets-and-maps.html#GUID-6A9BAE41-A1AD-4AA1-AF1A-A8FC99A14199 seems to imply that non mutable Map returned by Map.copyOf() is more space efficient.


Solution

HashMap is fairly close to optimal in most cases already. The array of buckets doubles in capacity each time, so it's most wasteful when you have (2^N) + 1 items, since the capacity will necessarily be 2^(N+1) (i.e. 2049 items require capacity of 4096, but 2048 items fit perfectly).

In your case, specifying an initial size will only prevent a few reallocations when the map is created, which if it only happens once probably isn't relevant. Load factor is not relevant because the map's capacity will never change. In any case, if you did want to pre-size, this would be correct:

new HashMap<>(numItems, 1);

Does the size of the map matter (20 elements vs 140,000)?

It will have an impact, but not a massive one. Items are grouped into buckets, and buckets are structured as lists or trees. So the performance is mostly dependent on how many items are in a given bucket, rather than the total number of items across all buckets.

What's important is how evenly distributed across your buckets the items are. A bad hash code implementation will result in clustering. Clustering will start to move O(1) operations towards O(log n), I believe.

// The worst possible hashCode impl.
@Override
public int hashCode() { return 0; } // or any other constant 

If you have the same items in the map across multiple invocations of your application (not clear from the question if that's the case), and if the class of the key is under your control, then you have the luxury of being able to tweak the hashCode implementation to positively affect the distribution, e.g. by using different prime numbers as a modulus. This would be trial and error, though, and is really only a micro-optimization.

As for the comments/answers addressing how to confer immutability, I'd argue that that's a separate concern. First work out what map is actually optimal, then worry about how to confer immutability upon it, if it isn't already. You can always wrap a mutable map in Collections.unmodifiableMap. Supposedly Guava's ImmutableMap is slower than HashMap, and I suspect other immutable variants will struggle to exceed the performance of HashMap too.



Answered By - Michael
Answer Checked By - Timothy Miller (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to print multiple Employee details with below requirement which collection type can be used in java?

 September 20, 2022     arrays, hashmap, java, multidimensional-array     No comments   

Issue

I want to store data as below format to any function of java collection and print the output:-

[
   { id->100, name->'praveen', mobile-9455104973 },
   { id->101, name->'Saurbh', mobile-7355078643 },
   { id->103, name->'Shivendr', mobile-123456789 } 
]

Output:

ID   Name       Mobile
100  Praveen    9455104973
101  Saurbh     735078643
102  Shivendra  123456789

Solution

I recommend that you create an employee class.

public class Employee {
private int id;
private String name;
private long phoneNumber;

/**
 * @param id
 * @param name
 * @param phoneNumber
 */
public Employee(int id, String name, long phoneNumber) {
    super();
    this.id = id;
    this.name = name;
    this.phoneNumber = phoneNumber;
}

@Override
public String toString() {
    return id + "\t" + name + "\t" + phoneNumber + "\n";
}
}

After that you create a list of employees and initialize it with the employees you are interested in and print it.

List<Employee> employees = new ArrayList<>();
    employees.add(new Employee(100, "praveen", 9455104973L));
    employees.add(new Employee(101, "Saurbh", 7355078643L));
    employees.add(new Employee(103, "Shivendr", 123456789L));
    
    System.out.println("ID\tName\tMobile");
    
    for (Employee e: employees)
        System.out.println(e.toString());

OUTPUT:

ID  Name    Mobile
100 praveen 9455104973

101 Saurbh  7355078643

103 Shivendr    123456789


Answered By - Fede Cana
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How collision between different HashMap objects is avoided?

 September 20, 2022     hash-collision, hashmap, java     No comments   

Issue

I have found that HashMaps calculate hashes for performance optimization. They use hashCode() to split up Keys into different buckets, and equals() for further comparison within those buckets.

However, I could not find an explanation of how collision between different HashMap objects is averted.

Current understanding:

  1. Different objects can have the same hash.
  2. Thus different Map Keys can end up in the same bucket.
  3. Keys of different maps can also have the same hash.
  4. Thus Keys of independent map objects can also end up in the same bucket.

If assumptions 3 and 4 are correct, would not it be possible for different HashMaps overwrite each others Values by accident? Or retrieve a Value that belongs to a wrong Map?

How is this avoided?

e.g.

HashMap<MyKey, Value> map1 = new HashMap<>();

HashMap<MyKey, Value> map2 = new HashMap<>();

Can MyKey values of map1 and map2 end up in the same bucket?

Can map2 instead of its own values start retrieving values of map1?


Solution

Different HashMap objects don't share buckets.

Your item #2 should be changed to "different map keys of the same HashMap can end up in the same bucket" and #4 is straight up wrong, as each HashMap has its own array of buckets to use that a totally independent of what any other HashMap does.



Answered By - Joachim Sauer
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I update a value in a mutable HashMap?

 September 20, 2022     hashmap, rust     No comments   

Issue

Here is what I am trying to do:

use std::collections::HashMap;

fn main() {
    let mut my_map = HashMap::new();
    my_map.insert("a", 1);
    my_map.insert("b", 3);

    my_map["a"] += 10;
    // I expect my_map becomes {"b": 3, "a": 11}
}

But this raises an error:

Rust 2015

error[E0594]: cannot assign to immutable indexed content
 --> src/main.rs:8:5
  |
8 |     my_map["a"] += 10;
  |     ^^^^^^^^^^^^^^^^^ cannot borrow as mutable
  |
  = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `std::collections::HashMap<&str, i32>`

Rust 2018

error[E0594]: cannot assign to data in a `&` reference
 --> src/main.rs:8:5
  |
8 |     my_map["a"] += 10;
  |     ^^^^^^^^^^^^^^^^^ cannot assign

I don't really understand what that means, since I made the HashMap mutable. When I try to update an element in a vector, I get the expected result:

let mut my_vec = vec![1, 2, 3];

my_vec[0] += 10;
println! {"{:?}", my_vec};
// [11, 2, 3]

What is different about HashMap that I am getting the above error? Is there a way to update a value?


Solution

Indexing immutably and indexing mutably are provided by two different traits: Index and IndexMut, respectively.

Currently, HashMap does not implement IndexMut, while Vec does.

The commit that removed HashMap's IndexMut implementation states:

This commit removes the IndexMut impls on HashMap and BTreeMap, in order to future-proof the API against the eventual inclusion of an IndexSet trait.

It's my understanding that a hypothetical IndexSet trait would allow you to assign brand-new values to a HashMap, and not just read or mutate existing entries:

let mut my_map = HashMap::new();
my_map["key"] = "value";

For now, you can use get_mut:

*my_map.get_mut("a").unwrap() += 10;

Or the entry API:

*my_map.entry("a").or_insert(42) += 10;


Answered By - Shepmaster
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is the method #each_index non existing for hashes in Ruby?

 September 20, 2022     arrays, hashmap, methods, ruby     No comments   

Issue

Why can I use #each and #each_with_index on both arrays and hashes, but the #each_index method can be used only on an array and not on a hash?


Solution

each_index

Iterates over array indexes.

Hashes don't have indexes. Hashes have keys. Use each_key.

Why do Hashes have each_with_index? Because that's part of the Enumerable module which both Hashes and Arrays include. Enumerable methods use shared terminology. Hashes and Arrays predate the Enumerable module, Array#each_index (sometime before v1.0r2) came before Enumerable#each_with_index (Feb 5th, 1998), so there is some overlap between Array, Hash, and Enumerable for backwards compatibility.



Answered By - Schwern
Answer Checked By - Senaida (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to create a HashMap with two keys (Key-Pair, Value)?

 September 20, 2022     hash, hashcode, hashmap, java     No comments   

Issue

I have a 2D array of Integers. I want them to be put into a HashMap. But I want to access the elements from the HashMap based on Array Index. Something like:

For A[2][5], map.get(2,5) which returns a value associated with that key. But how do I create a hashMap with a pair of keys? Or in general, multiple keys: Map<((key1, key2,..,keyN), Value) in a way that I can access the element with using get(key1,key2,...keyN).

EDIT : 3 years after posting the question, I want to add a bit more to it

I came across another way for NxN matrix.

Array indices, i and j can be represented as a single key the following way:

int key = i * N + j;
//map.put(key, a[i][j]); // queue.add(key); 

And the indices can be retrevied from the key in this way:

int i = key / N;
int j = key % N;

Solution

There are several options:

2 dimensions

Map of maps

Map<Integer, Map<Integer, V>> map = //...
//...

map.get(2).get(5);

Wrapper key object

public class Key {

    private final int x;
    private final int y;

    public Key(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Key)) return false;
        Key key = (Key) o;
        return x == key.x && y == key.y;
    }

    @Override
    public int hashCode() {
        int result = x;
        result = 31 * result + y;
        return result;
    }

}

Implementing equals() and hashCode() is crucial here. Then you simply use:

Map<Key, V> map = //...

and:

map.get(new Key(2, 5));

Table from Guava

Table<Integer, Integer, V> table = HashBasedTable.create();
//...

table.get(2, 5);

Table uses map of maps underneath.

N dimensions

Notice that special Key class is the only approach that scales to n-dimensions. You might also consider:

Map<List<Integer>, V> map = //...

but that's terrible from performance perspective, as well as readability and correctness (no easy way to enforce list size).

Maybe take a look at Scala where you have tuples and case classes (replacing whole Key class with one-liner).



Answered By - Tomasz Nurkiewicz
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing