How can i find the below map got synchronized - java

i am just synchronizing the HashMap using Collections.synchronizedMap(map); then adding values to the map as shown below. And in second scenario i have added keys and values to the map then i am doing synchronization to map object. But i did not find any difference in the output.
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SyncHashMap {
public static void main(String[] args) {
Map<Integer,String> map = new HashMap<Integer, String>();
map = Collections.synchronizedMap(map);
map.put(10, "ten");
map.put(20, "twenty");
map.put(30, "thirty");
map.put(40, "forty");
map.put(50, "fifty");
System.out.println(map);
}
}
Output:
{50=fifty, 20=twenty, 40=forty, 10=ten, 30=thirty}
In another scenario:
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SyncHashMap {
public static void main(String[] args) {
Map<Integer,String> map = new HashMap<Integer, String>();
map.put(10, "ten");
map.put(20, "twenty");
map.put(30, "thirty");
map.put(40, "forty");
map.put(50, "fifty");
map = Collections.synchronizedMap(map);
System.out.println(map);
}
}
Output:
{50=fifty, 20=twenty, 40=forty, 10=ten, 30=thirty}
Is there any difference in between these outputs. Otherwise any particular way to find difference in synchronizedMap method while using. Need some clarification.

Related

Sort <String,Double> HashMap using comparator and without TreeMap

Trying to sort HashMap of <String,Double> without using treeMap or other method. Need the code to pass a hashMap and return a sorted hashMap in the fastest time. What am I doing wrong with the string Comparator. Please look and advise. Thank you very much!!!
/// Here's the main
package Sort_String_Double_without_TreeMap;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class Main {
public static void main(String[] args) throws InterruptedException {
Map<String, Double> outGoing = new HashMap<>();
outGoing.put("J", -5.0);
outGoing.put("X", 0.7);
outGoing.put("C", 0.0);
outGoing.put("D", 80.0);
outGoing.put("A", 80.0);
System.out.println("---UNSORTED---");
System.out.println(outGoing);
TimeUnit.SECONDS.sleep(1);
Helper_SorterClass sorter = new Helper_SorterClass ();
System.out.println("---SORTED---");
System.out.println();
System.out.println("SIZE= " + sorter.SortHashMapKey(outGoing).size());
System.out.println(sorter.SortHashMapKey(outGoing));
}
}
And Here's the other class...
/// Here's the helper class
package Sort_String_Double_without_TreeMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Helper_SorterClass {
public Map<String, Double> SortHashMapKey(Map<String, Double> unsortedMap) {
List<String> list = new ArrayList(unsortedMap.keySet());
Collections.sort(list, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return String.valueOf(o1).compareTo(String.valueOf(o2));
}
});
Map<String, Double> sortedMap = new HashMap<>();
for (String keys : list) {
sortedMap.put(keys, unsortedMap.get(keys));
}
return sortedMap;
}
}
Unfortunately getting wrong output.
run:
---UNSORTED---
{A=80.0, C=0.0, D=80.0, X=0.7, J=-5.0}
---SORTED---
SIZE= 5
{A=80.0, C=0.0, D=80.0, X=0.7, J=-5.0}
BUILD SUCCESSFUL (total time: 1 second)
Map<String, Double> sortedMap = new HashMap<>();
for (String keys : list) {
sortedMap.put(keys, unsortedMap.get(keys));
}
you should use LinkedHashMap instead of HashMap as below:
Map<String, Double> sortedMap = new LinkedHashMap<>();
for (String keys : list) {
sortedMap.put(keys, unsortedMap.get(keys));
}
HashMap doesn't maintain insertion order. So once you put the entries in a new HashMap() after comparing, it will again give unsorted result when you iterate over the new map. But if you use a LinkedHashMap, it will maintain insertion order while iterating.

How to create a Guava HashMultiset from a Map<String, Object>

This doesn't compile:
Map<String, Object> map = new HashMap<String, Object>();
HashMultiset<Map<String, Object>> n1Properties = HashMultiset.create(map);
None of the overloaded create methods accepts a Map. But you can use the addAll method to add the Map converted to a Collection.
import com.google.common.collect.HashMultiset;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
public class SO {
public static void main(String args[]) {
Map<String, Object> map = new HashMap<>();
map.put("foo", "FOO");
map.put("bar", "BAR");
HashMultiset<Map<String, Object>> n1Properties = HashMultiset.create();
n1Properties.addAll(Collections.singleton(map));
System.out.println(n1Properties);
}
}
Output:
[{bar=BAR, foo=FOO}]

Cannot infer type arguments for hashmap<>

I am getting
Cannot infer type arguments for java.util.HashMap<>
for the following code
class Test {
public static void main(String[] args) {
Map<Integer, String> map = new HashMap<>();
map.put(1, "x");
map.put(2, "y");
map.put(3, "x");
map.put(4, "z");
//the following line has error
Map<String, ArrayList<Integer>> reverseMap = new java.util.HashMap<>(map.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue)).values().stream()
.collect(Collectors.toMap(item -> item.get(0).getValue(),
item -> new ArrayList<>(item.stream().map(Map.Entry::getKey).collect(Collectors.toList()))));
System.out.println(reverseMap);
}
}
What went wrong and Can anyone Explain me this ?
I have checked for proper imports and found out that I am importing java.util.hashmap and none other.
Still the pesky error is buging me.
That's a bug in ecj (eclipse compiler), you can work around it and add more type information :
item -> new ArrayList<Integer>(item.stream().map(Entry::getKey)
See how I've added ArrayList<Integer>.
It compiles fine with javac-8 and 9.
And btw seems like there is a simpler way to do things:
map.entrySet()
.stream()
.collect(Collectors.groupingBy(
Entry::getValue,
HashMap::new,
Collectors.mapping(Entry::getKey, Collectors.toList())));
In my case, the error disappeared after adding import java.util.Map; :
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.simple.SimpleJdbcInsert;
import com.fasterxml.jackson.databind.ObjectMapper;
public void saveFooOrder(Foo foo, long orderId) {
Map<String, Object> values = new HashMap<>();
/*^^^^ Error was here: Cannot
infer type arguments for HashMap<>*/
values.put("fooOrder", orderId);
values.put("foo", foo.getId());
orderFooInserter.execute(values);
}
your code is not completed, and you are missing a )
try doing:
import java.util.*;
import java.util.stream.Collectors;
public class HelloWorld{
public static void main(String []args){
Map<Integer, String> map = new HashMap<>();
map.put(1, "x");
map.put(2, "y");
map.put(3, "x");
map.put(4, "z");
Map<String, ArrayList<Integer>> reverseMap = new java.util.HashMap<>(map.entrySet().stream()
.collect(Collectors.groupingBy(Map.Entry::getValue)).values().stream()
.collect(Collectors.toMap(item -> item.get(0).getValue(),
item -> new ArrayList<>(item.stream().map(Map.Entry::getKey).collect(Collectors.toList())))));
System.out.println(reverseMap);
}
}
this produce the output
{x=[1, 3], y=[2], z=[4]}

How to add List of objects in a Map

I have a List and A is defined below.
How do i add in a Map with Key as Long and values as List of Strings.
Class A
{
Long in;
List<String> out;
}
Map<Long,List<String>>
Create a Hashmap object, with key Long and value List. Add items with put(key,value) and retrieve them with get
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<Long,List<String>> myMap=new HashMap<Long,List<String>>();
List<String> myList=new ArrayList<String>();
myList.add("abc");
myList.add("xyz");
myMap.put(new Long(1), myList);
for(int i=0;i<myList.size();i++)
System.out.println(myMap.get(new Long(1)).get(i));
}
}
1.) Create HashMap with Key as Long and value as List<String>.
2.) Use put method of HashMap, as below.
public static void main(String[] args) {
Map<Long, List<String>> myMap = new HashMap<Long, List<String>>();
myMap.put(101L, new ArrayList<String>());
}

How to Sort HashMap <String ,Object> using Object Value

I'm having trouble applying sorting mechanism through my application.
Reason was sometimes sort are not accurate and also the comparator thing in java still not clear for me, but i have used sort here and there.
Now, current problem is as follows.
I have
HashMap<String, ModelX.ContactModel> unsortedModelContacts =
new HashMap<String,ModelX.ContactModel>(contacts.size());
After that I fached
contactlist and using for loop I have put the values as follows:
unsortedModelContacts.put(stringvalue, modelContact);
//object having name , and other details
How can I sort the unsortedModelContacts sorting modelContact.getName property?
If your map's key is different from the name field then you can consider using this approach. Writing a separate comparator
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import sample.ModelX.ContactModel;
public class SortMapSample {
public static void main(String[] args) throws Exception {
Map<String, ModelX.ContactModel> unsortedModelContacts = new HashMap<String,ModelX.ContactModel>(10);
unsortedModelContacts.put("1", new ModelX.ContactModel("James"));
unsortedModelContacts.put("2", new ModelX.ContactModel("Mary"));
unsortedModelContacts.put("3", new ModelX.ContactModel("John"));
unsortedModelContacts.put("4", new ModelX.ContactModel("Amanda"));
unsortedModelContacts.put("5", new ModelX.ContactModel("Charles"));
System.out.println(sortMap(unsortedModelContacts));
}
private static Map<String, ModelX.ContactModel> sortMap(
Map<String, ModelX.ContactModel> unsortedMap) {
List<Entry<String, ModelX.ContactModel>> list = new LinkedList<Entry<String, ModelX.ContactModel>>(
unsortedMap.entrySet());
Collections.sort(list,
new Comparator<Entry<String, ModelX.ContactModel>>() {
#Override
public int compare(Entry<String, ContactModel> o1,
Entry<String, ContactModel> o2) {
return o1.getValue().getName().compareTo(o2.getValue().getName());
}
});
Map<String, ModelX.ContactModel> sortedMap = new LinkedHashMap<String, ModelX.ContactModel>();
for(Entry<String, ModelX.ContactModel> item : list){
sortedMap.put(item.getKey(), item.getValue());
}
return sortedMap;
}
}
SortedMap<String,ModelX.ContactModel> sortedModelContacts = new TreeMap<>();
for( ModelX.ContactModel modelContact: contactlist ){ // same list as before
sortedModelContacts.put( modelContact.getName(), modelContact);
}
You can now access entries of this map in sort order of the name property.
Note: this assumes that names are unique. If this isn't true, you'll have to use a multimap or
Map<String,ModelX.Set<ContactModel>>
and modify the put and other accesses accordingly.

Categories

Resources