Transfer all keys of a HashMap into ArrayList [duplicate] - java

This question already has answers here:
How does one convert a HashMap to a List in Java?
(8 answers)
Closed 5 years ago.
I am getting all the keys in a map into a HashSet.
I want to be able to transfer this into an ArrayList.

Did you mean this :
Map<K, V> map = new HashMap<>();
List<K> list = new ArrayList<>(map.keySet());

It appears you are already aware that Set<KeyType> set = map.keySet() returns a Set of the keys:
to put these into an ArrayList<KeyType> you can simply do new ArrayList(set);

Map<String,String> mymap = new HashMap<>();
// add data to the map
String[] array = mymap.keySet().toArray(new String[0]);

Why not use the addAll method?
Set<KeyType> keys = map.keySet();
List<KeyType> res = new ArrayList<>();
res.addAll(keys);
No?

Arrays.asList(map.keySet().toArray());
Would be a good place to start

Related

Is there a more elegant solution for filling a List from a Map? [duplicate]

This question already has answers here:
Best way to create a hashmap of arraylist
(9 answers)
java8 map how to add some element to a list value simply [duplicate]
(1 answer)
Closed 2 years ago.
I try to fill the List from the Map. In case the list is NULL I will create a new List and add a new created element otherwise add this element to existing list.
I'm wondering if there is a more elegant solution in JAVA8 for this.
Any help appreciated.
Map<String, List<MyObject>> myMap = new HashMap<>();
List<MyObject> list = myMap.get("key");
myMap.put("key", list == null ? Arrays.asList(new MyObject()) : Arrays.asList(list, new MyObject()));
Assuming Arrays.asList(list, new MyObject()) should instead add a new MyObject instance to list, then yes, you can use Map#computeIfAbsent to make the code more readable:
Map<String, List<MyObject>> myMap = new HashMap<>();
myMap.computeIfAbsent("key", key -> new ArrayList<>()).add(new MyObject());
If "key" is not present as a key in the Map, then a mapping will be created to a new ArrayList instance (which is returned). Otherwise, the existing List will be returned by the call to computeIfAbsent, allowing you to add a new element to it.
You could simply make sure your get doesn't return null in the first place:
List<MyObject> list = myMap.getOrDefault("key", new ArrayList<>);
Then you'll end up with
List<MyObject> list = myMap.getOrDefault("key", new ArrayList<>);
list.add(new MyObject());
myMap.put("key", list);

How to convert List<Map<String,String>> to Map<String,String> using java-8 lambda and stream [duplicate]

This question already has an answer here:
How to flatten List of Maps in java 8
(1 answer)
Closed 3 years ago.
I have below list of Map.
Map<String,String> map1 = new HashMap<>(); map1.put("DAY1","40T"); map1.put("DAY2","60T");
Map<String,String> map2 = new HashMap<>(); map2.put("DAY5","70T"); map2.put("DAY6","90T");
Map<String,String>[] mapArr= new Map[] {map1,map2};
List<Map<String,String>> lstOfMaps = Arrays.asList(mapArr);
How to convert the above lstOfMaps as Map<String,String> using java8.
Where Keys are DAY1,DAY2,DAY5,DAY6 and Values will be 40T,60T,70T,90T
I have tried in cople of ways but it was lengthy using a for loop. Trying to use lambdas and streams now.
The easiest solution would be to take the entry stream of each map in the list, flatten them into one stream, and collect that back into a map:
return lstOfMaps.stream().flatMap(map ->
map.entrySet().stream()
).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Delete entry from HashMap [duplicate]

This question already has answers here:
Iterate through a HashMap [duplicate]
(7 answers)
Closed 6 years ago.
I have a HashMap:
public static Map<String, Set<String>> adjMap = new HashMap<String, Set<String>>();
adjMap.put(title, new HashSet<String>());
adjMap.get(title).add(cutTitle(graphLink));
Now I want do delete all entries from the values (HashSet), which does not contains as a key.
Here is my code so far:
for(String s: adjMap.keySet()){
for(Set<String> s1: adjMap.values()){
for(String s2: s1){
if(!s.contains(s2)){
s1.remove(s2);
}
}
}
}
But I get an exception:
Exception in thread "main" java.util.ConcurrentModificationException
Iterate your Map
Iterator it = adjMap.entrySet().iterator();
while (it.hasNext())
{
Entry item = it.next();
map.remove(item.getKey());
}
I think for-each loops are not allowed to alter the iterated object. To remove entries you should use an iterator.
Compare to map-Iteration for an example.
You can use ConcurrentHashMap instead, or create a copy of your HashMap and make any changes to the copy.

Strings as key in Hashmap [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 6 years ago.
I'm newbie with Java
Is it possible to convert a String, or a String[] as the keys of an Hashmap?
I mean:
String keysToConvert = "key1,key2,key3";
into
HashMap<String, Double> hashmap = new HashMap<String, Double>();
[apply in some way the keys of the string]
hashmap.get("key2");
I know that hashmap.get("key2");has no value in this moment. I just would know if there is a way to load the keys in an HashMap.
hashmap.put("key2", 1.0d);
System.out.println(hashmap.get("key2")); // prints 1.0
This is the basic usage of a Map
If you have String[], you can add them using a for-each loop:
String[] keys = {"key1", "key2", "key3"};
HashMap<String, Double> hashmap = new HashMap<String, Double>();
for (String key : keys) {
hashmap.put(key, null);
}

How can you sort values in HashMap [duplicate]

This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 9 years ago.
For example you have a HashMap<String, String>
how can you sort values in the hashmap and print them to console
what would be the best ways to do it?
This should do it:
Map<String, String> asso = new HashMap<String, String>
// add some tuples to asso
List<String> values = new ArrayList(asso.values());
Collections.sort(values); // assumes an appropriate comparator implementation for the value type
There isn't a way to retrieve a HashMap tuple by value sorted order afaik.

Categories

Resources