Java.lang.ClassCastException: java.util.HashMap $ EntrySet cannot be passed to java.util.Map $ Entry

I have an overrriden method like this

@Override public Build auth (Map.Entry<String, String> auth) { this.mAuth = auth; return this; } 

Here I am trying to call this method as follows

 Map<String, String> authentication = new HashMap<String , String> (); authentication.put("username" , "testname"); authentication.put("password" , "testpassword"); Map.Entry<String, String> authInfo =(Entry<String , String>) authentication.entrySet(); AuthMethod.auth(authInfo) 

When starting this process, I get

 java.lang.ClassCastException: java.util.HashMap$EntrySet cannot be cast to java.util.Map$Entry 

How can I pass Map.Entry<String, String> to the auth method

+5
source share
6 answers

You are trying to create a set for one record.

You can use each entry element, iterating through a set:

 Iterator it = authentication.entrySet().iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); //current entry in a loop /* * do something for each entry */ } 
+4
source

Well yes.

You are trying to use Set<Map.Entry<String, String>> as one Map.Entry<String, String> .

You need to select an element in the set or iterate over each record and process it.

Something in the lines:

 for (Map.Entry<String, String> entry: authentication.entrySet()) { // TODO logic with single entry } 
+3
source
 Map.Entry<String, String> authInfo =(Entry<String, String>) authentication.entrySet(); 

Here you are making the wrong translation. You mentioned the auth method, which is expected to only expect username and password pairs. So something like below:

 Map<String, String> authentication = new HashMap<String, String>(); authentication.put("testname", "testpassword"); Map.Entry<String, String> authInfo = authentication.entrySet().iterator().next(); AuthMethod.auth(authInfo) 
+3
source

authentication.entrySet() is a collection of Entry . You can handle them all as follows:

  authentication.entrySet().stream().map(x->auth(x)).collect(Collectors.toList()) 
+1
source

If we want to return a specific record (string), we need to iterate the first record through iterator.next ():

 Map.Entry<String, String> authInfo = (Entry<String, String>) authentication.entrySet().iterator().next(); 

and if we want to iterate over the map, we need to save this as a loop:

 for( Map.Entry<String, String> authInfo : authentication.entrySet()){ System.out.println("authInfo:"+authInfo.getKey()); } 
+1
source

The following function can be taken as a link for general iteration, installation, obtaining values ​​for the map.

 (Iterator<Entry> i = entries.iterator(); i.hasNext(); ) { Map.Entry e = (Entry) i.next(); if(((String)e.getValue())==null ){ i.remove(); } else { e.setValue("false"); } System.out.println(e.getValue()); } 
+1
source

All Articles