Convert Map to Sorted List - java

I'm trying to convert a Map to an ordered List based upon the values in the Map.
Suppose I have the following:
Map<String, Integer> map = Maps.newHashMap();
map.put("foo", 1);
map.put("boo", 3);
map.put("bar", 2);
//list needs to be sorted by Integer Value -- ASC or DESC
List<String> list = //Elegant guava call? List should be: {foo, bar, boo}

List<String> list = Ordering.natural().onResultOf(Functions.forMap(map))
.sortedCopy(map.keySet());
...I think?

Related

Compare HashMap values and return first key

I've got HashMap
Map<String, Integer> map = new HashMap<>();
map.put("b", 2);
map.put("a", 2);
map.put("c", 2);
I need to compare values, and if it equals, I need to return first key value "b", but map return "a".
How can I achieve it?
In HashMap, keys are not ordered, so you cannot tell which key was first inserted.
Have a look at LinkedHashMap for a Map with ordered keys.
Hashmaps are not designed to search for values (i.e, they are designed to search for keys). You may want to create a different hashmap for this:
Map<Integer, ArrayList<String>> map2 = new HashMap<>();
ArrayList<String> arr = new ArrayList<>();
arr.add("b");
arr.add("a");
arr.add("c");
map2.put(2, arr);
map2.get(2).get(0); // returns "b", i.e, first element added into the array

How to sort a HashMap with key,value pair from an ArrayList in Java

Hi i have a ArrayList of HashMap and i need the HashMap to be sorted by its key,Value.
ArrayList<HashMap> newList = new ArrayList();
loop start:
HashMap hashData = new HashMap();
hashData.put("name", "string-studentname");
hashData.put("mark", "int-studentmark");
newList.add(hashData);
loop end:
I need the newList to be sorted by the key-mark.
How do i get it?
If you have multiple entries in your ArrayList and the key is the same, you can just sort via:
newList.sort(Comparator.comparingInt(o -> o.get("mark")));
Assuming you're typing the map properly:
HashMap<String, Integer> hashData = new HashMap<>();
hashData.put("mark", 1);

Map values to list

I have an Map<String,Integer> which is sorted by value like that
public void sortList(Map<String,Integer> map){
set = map.entrySet();
list = new ArrayList<Map.Entry<String, Integer>>(set);
Collections.sort( list, (o1, o2) -> (o2.getValue()).compareTo( o1.getValue() ));
}
I need to copy all values to new list
word_used = new ArrayList<Integer>(map.values());
but it saves in non-sorted order
When you sort that list you created from the entrySet, it doesn't change the order of the entries in the original Map. You'll have to return the list from your sortList method if you want a List of the sorted values.
map.values() will not return the values sorted, since the values are not kept in any specific order in the Map. Some Map implementations (such as TreeMap) keep the keys sorted, but not the values.
First extract the list, sort it and then create a new list with it.
List<Integer> tmp = map.values();
Collections.sort(tmp);
word_used = new ArrayList<Integer>(tmp);
java-8
word_used = new ArrayList<Integer>(map.values()
.stream()
.sorted()
.collect(Collectors.toList()));

search string in HashMap combine ArrayList on android

I am trying listItem.indexOf(word.text)==-1 to find the string I want.
Using indexOf function in single ArrayList is working fine. but after I use HashMap combine ArrayList, the indexOf function seems not working.
Any solution? thx!
ArrayList<HashMap<String, Object>> listItem= new ArrayList<HashMap<String,Object>>();
SimpleAdapter mSimpleAdapter = new SimpleAdapter(this,listItem, R.layout.item_main, new String[] {"ItemImage","ItemTitle", "ItemText"},
new int[] {R.id.ItemImage,R.id.ItemTitle,R.id.ItemText});
if(listItem.indexOf(word.text)==-1){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", R.drawable.speak2);
map.put("ItemTitle", word.text);
map.put("ItemText", temp);
listItem.add(map);
}
I'm assuming that word.text is a String. Therefore you have no reason to expect that listItem.indexOf(word.text) would find it in a List that contains HashMap instances.
It looks like you are storing word.text as one of the values of a HashMap stored in the list. To search for a HashMap in the List that contains this value you have to iterate over all the Maps in the List, and for each Map, iterate over all its values.
Perhaps a better data structure would be HashMap<String,HashMap<String, Object>, where the key is taken from word.text and the value is the HashMap you currently store in the list. This way, you could replace listItem.indexOf(word.text) with mapItem.containsKey(word.text), which is more efficient, and would work.
HashMap<String,HashMap<String, Object>> mapItem= new HashMap<String,HashMap<String,Object>>();
if(!mapItem.containsKey(word.text)){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", R.drawable.speak2);
map.put("ItemTitle", word.text);
map.put("ItemText", temp);
mapItem.put(word.text, map);
}

How do I convert a Map to List in Java?

How do I convert a Map<key,value> to a List<value>? Should I iterate over all map values and insert them into a list?
List<Value> list = new ArrayList<Value>(map.values());
assuming:
Map<Key,Value> map;
The issue here is that Map has two values (a key and value), while a List only has one value (an element).
Therefore, the best that can be done is to either get a List of the keys or the values. (Unless we make a wrapper to hold on to the key/value pair).
Say we have a Map:
Map<String, String> m = new HashMap<String, String>();
m.put("Hello", "World");
m.put("Apple", "3.14");
m.put("Another", "Element");
The keys as a List can be obtained by creating a new ArrayList from a Set returned by the Map.keySet method:
List<String> list = new ArrayList<String>(m.keySet());
While the values as a List can be obtained creating a new ArrayList from a Collection returned by the Map.values method:
List<String> list = new ArrayList<String>(m.values());
The result of getting the List of keys:
Apple
Another
Hello
The result of getting the List of values:
3.14
Element
World
Using the Java 8 Streams API.
List<Value> values = map.values().stream().collect(Collectors.toList());
map.entrySet() gives you a collection of Map.Entry objects containing both key and value. you can then transform this into any collection object you like, such as new ArrayList(map.entrySet());
a list of what ?
Assuming map is your instance of Map
map.values() will return a Collection containing all of the map's values.
map.keySet() will return a Set containing all of the map's keys.
I guess you want to convert the values contained in the Map to a list? Easiest is to call the values() method of the Map interface. This will return the Collection of value objects contained in the Map.
Note that this Collection is backed by the Map object and any changes to the Map object will reflect here. So if you want a separate copy not bound to your Map object, simply create a new List object like an ArrayList passing the value Collection as below.
ArrayList<String> list = new ArrayList<String>(map.values());
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("java", 20);
map.put("C++", 45);
Set <Entry<String, Integer>> set = map.entrySet();
List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>(set);
we can have both key and value pair in list.Also can get key and value using Map.Entry by iterating over list.
If you want to ensure the values in the resultant List<Value> are in the key-ordering of the input Map<Key, Value>, you need to "go via" SortedMap somehow.
Either start with a concrete SortedMap implementation (Such as TreeMap) or insert your input Map into a SortedMap before converting that to List. e.g.:
Map<Key,Value> map;
List<Value> list = new ArrayList<Value>( new TreeMap<Key Value>( map ));
Otherwise you'll get whatever native ordering the Map implementation provides, which can often be something other than the natural key ordering (Try Hashtable or ConcurrentHashMap, for variety).
// you can use this
List<Value> list = new ArrayList<Value>(map.values());
// or you may use
List<Value> list = new ArrayList<Value>();
for (Map.Entry<String, String> entry : map.entrySet())
{
list.add(entry.getValue());
}
Map<String, String > map = new HapshMap<String, String>;
map.add("one","java");
map.add("two", "spring");
Set<Entry<String, String>> set = map.entrySet();
List<Entry<String, String>> list = new ArrayList<Entry<String, String>> (set);
for(Entry<String, String> entry : list) {
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
Here's the generic method to get values from map.
public static <T> List<T> ValueListFromMap(HashMap<String, T> map) {
List<T> thingList = new ArrayList<>();
for (Map.Entry<String, T> entry : map.entrySet()) {
thingList.add(entry.getValue());
}
return thingList;
}
public List<Object> convertMapToList(Map<Object, Object> map){
return new ArrayList<>(map.values());
}
If you want an immutable copy of the values:
List<Value> list = List.copyOf(map.values())

Categories