how to get hashmap values depends on key - java

i have this hashmap with string and arraylis:
Map<String, ArrayList<String>> devNameType = new HashMap<String, ArrayList<String>>();
public void kimenetPV(String name){
//létrehozom a nevet
String devName = name;
//létrehozom a kimeneteket tartalmazó arraylistet
ArrayList<String> outputs = new ArrayList<String>();
// 2. hozzáadaom az elemeket
outputs.add("EM A");
outputs.add("EM B");
outputs.add("AOUT1");
outputs.add("AOUT2");
devNameType.put(devName, outputs);
Iterator iter = devNameType.entrySet().iterator();
//kilistázom az elemeket
while (iter.hasNext()) {
Map.Entry mEntry = (Map.Entry) iter.next();
System.out.println(mEntry.getKey() + " : " + mEntry.getValue());
}
}
how can i print all the values?
Sorry for the begginer question i'm using the hashmaps for first time.

You can print the key:value pairs as this:
Iterator<Entry<String, List<String>>> iter = devNameType.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, List<String>> next = iter.next();
List<String> value = next.getValue();
System.out.println("key = " + next.getKey());
System.out.println("values : ");
for (String str : value) {
System.out.println(str);
}
}

for (List<String> value : devNameType.values()) {
... do something with this value
}
For key/value:
for (String key: devNameType.keySet()) {
List<String> values = devNameType.get(key);
... do something with the name and values
}
See http://docs.oracle.com/javase/6/docs/api/java/util/Map.html#values() and
http://docs.oracle.com/javase/6/docs/api/java/util/Map.html#keySet()

With hashMap.values() you get a Collection of all values:
http://developer.android.com/reference/java/util/HashMap.html#values()

Related

is it possible to print the keys of a hashmap with a specific form?

I'm about working with Junit test , hashmap in java .
My code looks like :
HashMap <String,String> var = new HashMap <String,String>();
var.put("key1","value1");
var.put("key2","value2");
var.put("key3","value3");
var.put("key4","value4");
Iterator<String> itKey = var.keySet().iterator();
String Existing_coaches = "" ;
while(itKey.hasNext()){
String key = (String)itKey.next();
// Existing_coaches = i use concat function
}
return Existing_coaches ;
What i want to do is to return the itkeys as this forms :
key1, key2, key3, key4
we start with the first key + comma etc .
so i need to know what's the first key and the last one .
Any idea on how we can do that ?
Join the keys with a comma and a space:
import java.util.*;
public class MyClass {
public static void main(String args[]) {
Map<String, String> m = new LinkedHashMap<>();
m.put("key1", "val1");
m.put("key2", "val2");
m.put("key3", "val3");
m.put("key4", "val4");
System.out.println(String.join(", ", m.keySet()));
}
}
Output:
key1, key2, key3, key4
Map<String, String> map = new LinkedHashMap<>();
// Approach 1 : use advanced for (foreach) loop
StringBuilder keyString = new StringBuilder();
for(String key: map.keySet()){
keyString = keyString.append(key + ", ");
}
String resultStr = keyString.toString().substring(0, keyString.toString().length()-2); // deducting 2 for comma and space
System.out.println(resultStr);
// Approach 2: use for loop
StringBuilder keyString2 = new StringBuilder();
Object[] keySet = (Object[]) map.keySet().toArray();
for(int i=0; i < keySet.length; i++) {
if(i == keySet.length-1) {
keyString2 = keyString2.append(keySet[i].toString());
} else {
keyString2 = keyString2.append(keySet[i].toString() + ", ");
}
}
System.out.println(keyString2.toString());
// Approach 3: Use String join
System.out.println(String.join(", ", map.keySet()));
If you are not familiar with String.join, use the first one, or use the second if you like it. Both ways work:
import java.util.HashMap;
import java.util.Iterator;
public class Hash {
public static void main(String args[]) {
HashMap <String, String> var = new HashMap <String, String>();
var.put("A", "1");
var.put("B", "2");
var.put("C", "3");
var.put("D", "4");
System.out.println("method 1: " + myHash(var));
System.out.println("method 2: " + myHash2(var));
}
public static String myHash(HashMap var) {
Iterator<String> itKey = var.keySet().iterator();
String Existing_coaches = "" ;
while(itKey.hasNext()){
String key = (String)itKey.next();
Existing_coaches = Existing_coaches + key + ", ";
}
return Existing_coaches.substring(0, Existing_coaches.length() -2) ;
}
public static String myHash2(HashMap var) {
return String.join(", ", var.keySet());
}
}
Output is:
method 1: A, B, C, D
method 2: A, B, C, D

How do I sort the words by the number of occuerences? [duplicate]

This question already has answers here:
Sort a Map<Key, Value> by values
(64 answers)
Closed 7 years ago.
So far I have been able to display the number of occurrence of each word but how can I sort the words by the number of occurrences?
import java.util.*;
public class CountOccurrenceOfWords {
public static void main(String[] args) {
String text = "Hello, I am a working class citizen who is independent and driven to be the best that I can be";
Map<String, Integer> map = new TreeMap<>();
String[] words = text.split("[\\s+\\p{P}]");
for (int i = 0; i < words.length; i++) {
String key = words[i].toLowerCase();
if (key.length() > 0) {
if (!map.containsKey(key)) {
map.put(key, 1);
}
else {
int value = map.get(key);
value++;
map.put(key, value);
}
}
}
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for(Map.Entry<String, Integer> entry: entrySet)
System.out.println(entry.getKey() + "\t" + entry.getValue());
}
}
You could get what you want by using a comparator.
For example:
static Comparator<String> DescendingFrequencyComparator = new Comparator<String>() {
public int compare(String s1, String s2) {
return map.get(s2).compareTo(map.get(s1));
}
};
Then use it as:
ArrayList<String> allWords = new ArrayList<String>(map.keySet());
allWords.sort(DescendingFrequencyComparator);
for(String s: allWords) {
System.out.println(s + "\t" + map.get(s));
}
something like
public LinkedHashMap sortHashMapByValues(HashMap passedMap) {
List mapKeys = new ArrayList(passedMap.keySet());
List mapValues = new ArrayList(passedMap.values());
Collections.sort(mapValues);
Collections.sort(mapKeys);
LinkedHashMap sortedMap = new LinkedHashMap();
Iterator valueIt = mapValues.iterator();
while (valueIt.hasNext()) {
Object val = valueIt.next();
Iterator keyIt = mapKeys.iterator();
while (keyIt.hasNext()) {
Object key = keyIt.next();
String comp1 = passedMap.get(key).toString();
String comp2 = val.toString();
if (comp1.equals(comp2)){
passedMap.remove(key);
mapKeys.remove(key);
sortedMap.put((String)key, (Double)val);
break;
}
}
}
return sortedMap;
}
public static void main(String[] args) {
ArrayList<Integer> wordsList = new ArrayList<>();
String text = "Hello, I am a working class citizen who is independent and driven to be the best that I can be";
Map<String, Integer> map = new TreeMap<>();
String[] words = text.split("[\\s+\\p{P}]");
for (int i = 0; i < words.length; i++) {
String key = words[i].toLowerCase();
if (key.length() > 0) {
if (!map.containsKey(key)) {
map.put(key, 1);
} else {
int value = map.get(key);
value++;
map.put(key, value);
}
}
}
Set<Map.Entry<String, Integer>> entrySet = map.entrySet();
for (Map.Entry<String, Integer> entry : entrySet){
System.out.println(entry.getKey() + "\t" + entry.getValue());
for (int i=0; i<entrySet.size(); i++){
wordsList.add(entry.getValue());
}
for(Integer counter : wordsList){
System.out.println(counter);
}
}

Using LinkedList with sort method

I am currently trying to use a LinkedList to print a list of keys from their highest number of occurences to lowest. I am trying to use the sort method on the getValue method of the entry but it is not working. Any ideas what I'm doing wrong. Here is a snippet of my code
// Beginning tree map
Map<String, Integer> map1 = new TreeMap<>();
String[] words1 = text.split("[ \n\t\r.,;:!?(){ ]");
for (int i = 0; i < words1.length; i++)
{
String key = words1[i].toLowerCase();
if (key.length() > 0)
{
if (!map1.containsKey(key))
{
map1.put(key, 1);
}
else
{
int value = map1.get(key);
value++;
map1.put(key, value);
}
}
}
Set<Map.Entry<String, Integer>> entrySet1 = map1.entrySet();
// Get key and value from each entry
System.out.println("Treemap: " + map1);
for (Map.Entry<String, Integer> entry: entrySet1)
System.out.println(entry.getValue() + "\t" + entry.getKey());
System.out.println("");
// Beginning for LinkedList
LinkedList<Entry<String, Integer>> linkedList = new LinkedList<>(entrySet1);
System.out.println("linkedList:");
System.out.println(linkedList);
System.out.println(linkedList.sort(entrySet1.getKey());
With my current output
Treemap: {a=2, class=1, fun=1, good=3, have=3, morning=1, visit=1}
2 a
1 class
1 fun
3 good
3 have
1 morning
1 visit
linkedList:
[a=2, class=1, fun=1, good=3, have=3, morning=1, visit=1]
So my ultimate question is, how can i pass my getValue method to the LinkedList in order to print them in a sorted order.

How to find the count of values for each key in a linked hashmap where the key and value are words

for(String j1:word1.keySet())
{
System.out.println(j1+"\t"+word1.get(j1));
}
This code gives the count of all words in the hashmap. I have the input as:
movie good
song bad
music good
movie super
How do I find the count of the words related to each key?
It should produce the result:
movie 2
song 1
music 1
good 2
bad 1
super 1
I think you want to print the total count of all the Strings appeared in the LinkedHashMap
public class Test {
//using a HashMap to keep count of all the words
private static Map<String, Integer> countMap = new HashMap<String, Integer>();
public static void main(String[] args) {
LinkedHashMap<String, String> words1 = new LinkedHashMap<String, String>();
words1.put("a", "movie good");
words1.put("b", "song bad");
words1.put("c", "music good");
words1.put("d", "movie super");
countWords(words1);
}
public static void countWords(LinkedHashMap word1){
Set keys = word1.keySet();
Iterator itr = keys.iterator();
while(itr.hasNext()){
String value = (String) word1.get(itr.next());
String[] valueArray = value.split(" ");
for(String s:valueArray){
Integer count = countMap.get(s);
if(count != null){
countMap.put(s, ++count);
}else{
countMap.put(s, 1);
}
}
}
//print the final count of all the words
for(Entry<String, Integer> entrySet: countMap.entrySet()){
System.out.println(entrySet.getKey() + " " + entrySet.getValue());
}
}
}

Reverse Map.key, map.value output

I have this output and it comes out in the opposite order. The last printout is what i want to be the first print out. How can I reverse it? It is a HashMap.
System.out.println();
int c = 0;
System.out.print(newName + "= ");
for (Map.Entry<Integer, Integer> entry : result.entrySet()) {
System.out.print(entry.getValue() + "X^" + entry.getKey());
c++;
if (c != result.size()) {
System.out.print("+");
}
To preserve insertion order when iterating use a LinkedHashMap instead of a HashMap, and to go in reverse do this:
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(result.entrySet());
Collections.reverse(entries);
for (Map.Entry<Integer, Integer> entry : entries) {
// same body as before
}
Alternatively, we can use a reverse iterator:
List<Map.Entry<Integer, Integer>> entries = new ArrayList<>(result.entrySet());
ListIterator<Map.Entry<Integer, Integer>> iter = entries.listIterator();
while (iter.hasPrevious()) {
Map.Entry<Integer, Integer> entry = iter.previous();
// same body as before
}

Categories

Resources