Can I pass a key of a value into variable in hashmap?
For example I have a key 987456321 for value "A". How to pass the key in a variable so that I can further subdivide the key and print it as 987-654-321,
by taking 987 as first,
654 as middle,
321 as last
So that I can print
first+ "-" + middle+ "-" + last as 987-654-321
by using toString() method.
I am new to Java, So help me Please
public static void main(String[] args)
{
HashMap<Long, String> hashMap = new HashMap<>();
hashMap.put(987456321L, "A");
hashMap.put(321654998L, "B");
hashMap.put(874563210L, "C");
hashMap.put(987453216L, "B");
hashMap.put(321650123L, "C");
hashMap.put(874568745L, "C");
System.out.println("Size of Map:"+hashMap.size());
System.out.println("Enter no: ");
userInput = new Scanner(System.in);
no = userInput.nextLong();
String name = hashMap.get(no);
System.out.println(name);
for (Map.Entry<Long, String> entry : hashMap.entrySet())
{
String key = entry.getKey().toString();
String value = entry.getValue();
System.out.println("name " + value + "- Number " + key);
}
}
You can iterate over all key-value-pairs of your map like this:
for (final Map.Entry<String, String> entry : map.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
// do whatever you need to do with key
}
If you're interested in a key for a certain value only - makes not much sense as the same value might be stored in a map with different keys - you will need to check for the value in the above loop until you found the key-value-pair of interest. E.g.:
if (Objects.equals(value, "A")) {
// do something with the key for value "A"
}
1. Solution for specific value:
This method returns keys for your value
public static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
Set<T> keys = new HashSet<T>();
for (Entry<T, E> entry : map.entrySet()) {
if (Objects.equals(value, entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
Now all you have to do is to iterate through returned set and do what you want with variable which contains your key
for (Long key : set) {
String s = String.valueOf(key);
}
Related
Is it possible to do so? If yes, what is the required syntax/method?
I tried it by using,
System.out.println(key+"="+HM.get(key));
but it prints it in this format,
key= value
whereas, I need
key=value
(Due to outputting format in HackerRank)
while(sc.hasNextLine())
{
String s=sc.nextLine();
if(a.containsKey(s))
{
System.out.println(s+"="+a.get(s));
}
else
System.out.println("Not found");
}
EDIT 1:
I saw the solution given, the person used the following code,
while(scan.hasNext()){
String s = scan.next();
Integer phoneNumber = phoneBook.get(s);
System.out.println(
(phoneNumber != null)
? s + "=" + phoneNumber
: "Not found"
);
}
Now, why does this not have white space in the answer?
The only visible change I see is that this person used an object instead of primitive data type.
Also,this person used int instead of string in accepting the phone number, I initially did the same but it gave me an InputMismatchException .
There is no avalilable method in https://docs.oracle.com/javase/7/docs/api/java/util/Map.html to get Entity from map if there is any key or value available. Try below code if it help :
if (map.containsKey(key)) {
Object value = map.get(key);
System.out.println("Key : " + key +" value :"+ value);
}
You can use entrySet() (see entrySet) to iterate over your map.
You will then have access to a Map Entry which contains the methods getValue() and getKey() to retreive both the value and the key of your mapped object.
entrySet() returns a Set, and Set extends Collection, which offers the stream() method, so you can use stream to loop over and process your entrySet :
map
.entrySet() // get a Set of Entries of your map
.stream() // get Set as Stream
.forEach( // loop over Set
entry -> // lambda as looping over set entries implicitly returns an Entry
System.out.println(
entry.getKey() // get the key
+ "="
+ entry.getValue() // get the value
);
If needed, you can add .filter() to process only elements that matches your conditions in your Stream.
Working example here
import java.util.HashMap;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<String, String> myMap = new HashMap<String, String>() {
private static final long serialVersionUID = 1L;
{
for (int i = 1 ; i < 10 ; i++) {
put("key"+i, "value"+i);
}
}
};
myMap.entrySet().stream().forEach(
entry -> System.out.println(entry.getKey() + "=" + entry.getValue())
);
}
}
Output :
key1=value1
key2=value2
key5=value5
key6=value6
key3=value3
key4=value4
key9=value9
key7=value7
key8=value8
class hello {
string name;
int number;
}
class object {
public static void main(string args[]) {
HashMap hs = new HashMap();
hello c1 = new hello();
hello c2 = new hello();
hs.put("india",c1);
hs.put("america",c2);
}
}
how to print he key value pairs
key with multiple values how is it printed
Iterate Map or HashMap like this.
Map<String, Hello> map=new HashMap<>();
Set<Entry<String, Hello>> entries=map.entrySet();
for (Entry<String, Hello> entry : entries) {
String key=entry.getKey();
Hello hello=entry.getValue();
}
With Java 8:
map.forEach((key, value) -> System.out.println(key + ", " + value));
You need to iterate over hash map keys, then print the key with its value.
Example:
HashMap<String, hello> map = new HashMap<String, hello>();
for (Iterator<String> iterator = map.keySet().iterator(); iterator.hasNext();) {
String key = iterator.next();
System.out.println(key + map.get(keu).toString); suppose you already override the toString method in your hello class
}
You can iterate using Entry Set too.
HashMap<String,hello> hs=new HashMap<String, hello>();
// Put values for hashMap.
for(Map.Entry<String, hello> printPairs: hs.entrySet()) {
System.out.print(printPairs.getKey()+" ---- ");
System.out.println(printPairs.getValue());
}
I have following LinkedHashMap declaration.
LinkedHashMap<String, ArrayList<String>> test1
my point is how can i iterate through this hash map.
I want to do this following, for each key get the corresponding arraylist and print the values of the arraylist one by one against the key.
I tried this but get only returns string,
String key = iterator.next().toString();
ArrayList<String> value = (ArrayList<String> )test1.get(key)
for (Map.Entry<String, ArrayList<String>> entry : test1.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
// now work with key and value...
}
By the way, you should really declare your variables as the interface type instead, such as Map<String, List<String>>.
I'm assuming you have a typo in your get statement and that it should be test1.get(key). If so, I'm not sure why it is not returning an ArrayList unless you are not putting in the correct type in the map in the first place.
This should work:
// populate the map
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.put("key1", new ArrayList<String>());
test1.put("key2", new ArrayList<String>());
// loop over the set using an entry set
for( Map.Entry<String,List<String>> entry : test1.entrySet()){
String key = entry.getKey();
List<String>value = entry.getValue();
// ...
}
or you can use
// second alternative - loop over the keys and get the value per key
for( String key : test1.keySet() ){
List<String>value = test1.get(key);
// ...
}
You should use the interface names when declaring your vars (and in your generic params) unless you have a very specific reason why you are defining using the implementation.
In Java 8:
Map<String, List<String>> test1 = new LinkedHashMap<String, List<String>>();
test1.forEach((key,value) -> {
System.out.println(key + " -> " + value);
});
You can use the entry set and iterate over the entries which allows you to access both, key and value, directly.
for (Entry<String, ArrayList<String>> entry : test1.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
I tried this but get only returns string
Why do you think so? The method get returns the type E for which the generic type parameter was chosen, in your case ArrayList<String>.
// iterate over the map
for(Entry<String, ArrayList<String>> entry : test1.entrySet()){
// iterate over each entry
for(String item : entry.getValue()){
// print the map's key with each value in the ArrayList
System.out.println(entry.getKey() + ": " + item);
}
}
I want to store values and retrieve them from a Java HashMap.
This is what I have so far:
public void processHashMap()
{
HashMap hm = new HashMap();
hm.put(1,"godric gryfindor");
hm.put(2,"helga hufflepuff");
hm.put(3,"rowena ravenclaw");
hm.put(4,"salazaar slytherin");
}
I want to retrieve all Keys and Values from the HashMap as a Java Collection or utility set (for example LinkedList).
I know I can get the value if I know the key, like this:
hm.get(1);
Is there a way to retrieve key values as a list?
I use these three ways to iterate a map. All methods (keySet, values, entrySet) return a collection.
// Given the following map
Map<KeyClass, ValueClass> myMap;
// Iterate all keys
for (KeyClass key : myMap.keySet())
System.out.println(key);
// Iterate all values
for (ValueClass value : myMap.values())
System.out.println(value);
// Iterate all key/value pairs
for (Entry<KeyClass, ValueClass> entry : myMap.entrySet())
System.out.println(entry.getKey() + " - " + entry.getValue());
Since Java 8 i often use Streams with lambda expressions.
// Iterate all keys
myMap.keySet().stream().forEach(key -> System.out.println(key));
// Iterate all values
myMap.values().parallelStream().forEach(value -> System.out.println(value));
// Iterate all key/value pairs
myMap.entrySet().stream().forEach(entry -> System.out.println(entry.getKey() + " - " + entry.getValue()));
Java Hashmap key value example:
public void processHashMap() {
//add keys->value pairs to a hashmap:
HashMap hm = new HashMap();
hm.put(1, "godric gryfindor");
hm.put(2, "helga hufflepuff");
hm.put(3, "rowena ravenclaw");
hm.put(4, "salazaar slytherin");
//Then get data back out of it:
LinkedList ll = new LinkedList();
Iterator itr = hm.keySet().iterator();
while(itr.hasNext()) {
String key = itr.next();
ll.add(key);
}
System.out.print(ll); //The key list will be printed.
}
map.keySet() would give you all the keys
//import statements
import java.util.HashMap;
import java.util.Iterator;
import java.util.TreeMap;
// hashmap test class
public class HashMapTest {
public static void main(String args[]) {
HashMap<Integer,String> hashMap = new HashMap<Integer,String>();
hashMap.put(91, "India");
hashMap.put(34, "Spain");
hashMap.put(63, "Philippines");
hashMap.put(41, "Switzerland");
// sorting elements
System.out.println("Unsorted HashMap: " + hashMap);
TreeMap<Integer,String> sortedHashMap = new TreeMap<Integer,String>(hashMap);
System.out.println("Sorted HashMap: " + sortedHashMap);
// hashmap empty check
boolean isHashMapEmpty = hashMap.isEmpty();
System.out.println("HashMap Empty: " + isHashMapEmpty);
// hashmap size
System.out.println("HashMap Size: " + hashMap.size());
// hashmap iteration and printing
Iterator<Integer> keyIterator = hashMap.keySet().iterator();
while(keyIterator.hasNext()) {
Integer key = keyIterator.next();
System.out.println("Code=" + key + " Country=" + hashMap.get(key));
}
// searching element by key and value
System.out.println("Does HashMap contains 91 as key: " + hashMap.containsKey(91));
System.out.println("Does HashMap contains India as value: " + hashMap.containsValue("India"));
// deleting element by key
Integer key = 91;
Object value = hashMap.remove(key);
System.out.println("Following item is removed from HashMap: " + value);
}
}
You can use keySet() to retrieve the keys.
You should also consider adding typing in your Map, e.g :
Map<Integer, String> hm = new HashMap<Integer, String>();
hm.put(1,"godric gryfindor");
hm.put(2,"helga hufflepuff");
hm.put(3,"rowena ravenclaw");
hm.put(4,"salazaar slytherin");
Set<Integer> keys = hm.keySet();
void hashMapExample(){
HashMap<String, String> hMap = new HashMap<String, String>();
hMap.put("key1", "val1");
hMap.put("key2", "val2");
hMap.put("key3", "val3");
hMap.put("key4", "val4");
hMap.put("key5", "val5");
if(hMap != null && !hMap.isEmpty()){
for(String key : hMap.keySet()){
System.out.println(key+":"+hMap.get(key));
}
}
}
I want to retrieve k,v-pairs from a HashMap.
The entrys are like this:
a = 3,4
b = 5,6
and so on. I need combinations of these values.
a=3, b=5
a=3, b=6
a=4, b=5
a=4, b=6
I don't know how many keys and how many entrys the values have. With entrySet I can get the values but not combinations. It looks like recursion but how?
Here's my code:
HashMap<String, String[]> map = new HashMap<String, String[]>();
BufferedReader file = new BufferedReader(new FileReader("test.txt"));
String str;
while ((str = file.readLine()) != null) {
// ... logic
map.put(key, value);
}
System.out.println("number of keys: " + map.size());
for (Map.Entry<String, String[]> entry : map.entrySet()) {
for (String value : entry.getValue()) {
System.out.println(entry.getKey() + ": " + value);
}
}
file.close();
You can try the following code:
public void mapPermute(Map<String, String[]> map, String currentPermutation) {
String key = map.keySet().iterator().next(); // get the topmost key
// base case
if (map.size() == 1) {
for (String value : map.get(key)) {
System.out.println(currentPermutation + key + "=" + value);
}
} else {
// recursive case
Map<String, String[]> subMap = new HashMap<String, String[]>(map);
for (String value : subMap.remove(key)) {
mapPermute(subMap, currentPermutation + key + "=" + value + ", ");
}
}
}
No guarantees on memory efficiency or speed. If you want to preserve the order of the keys in the map, you will have to pass in a TreeMap and change the code to use a TreeMap under the recursive case.
As the base case suggests, I'm assuming you have at least one entry in your map.
You can obtain a Cartesian product of map key-value combinations using a map and reduce approach.
Try it online!
Map<String, String[]> map = Map.of(
"a", new String[]{"3", "4"},
"b", new String[]{"5", "6"});
List<Map<String, String>> comb = map.entrySet().stream()
// Stream<List<Map<String,String>>>
.map(e -> Arrays.stream(e.getValue())
.map(v -> Map.of(e.getKey(), v))
.collect(Collectors.toList()))
// summation of pairs of list into a single list
.reduce((list1, list2) -> list1.stream()
// combinations of inner maps
.flatMap(map1 -> list2.stream()
// concatenate into a single map
.map(map2 -> {
Map<String, String> m = new HashMap<>();
m.putAll(map1);
m.putAll(map2);
return m;
}))
// list of combinations
.collect(Collectors.toList()))
// otherwise, an empty list
.orElse(Collections.emptyList());
// output, order may vary
comb.forEach(System.out::println);
Output, order may vary:
{a=3, b=5}
{a=3, b=6}
{a=4, b=5}
{a=4, b=6}
See also: Cartesian product of map values
It looks to me like you really want a MultiMap. In particular, ArrayListMultimap allows duplicate entries:
ArrayListMultimap<String, String> map = ArrayListMultimap.create();
for each line in file:
parse key k
for each value in line:
parse value v
map.put(k, v);
for (Map.Entry<String, String> entry : map.entries()) {
String key = entry.getKey();
String value = entry.getValue();
}
If you want a cartesian product of maps, you could compute that directly using recursion, or you could iterate over the maps: create a list of iterators and iterate odometer-style; when iterator N reaches its end, advance iterator N+1 and reset iterators 1..N.
Just poked around and found this SO question.
So I'd recommend you use guava's Sets.cartesianProduct for the cartesian product. Here's my poking around code, which you could adapt to your input logic:
String key1 = "a";
Set<Integer> values1 = Sets.newLinkedHashSet(Arrays.asList(1, 2, 3, 4));
String key2 = "b";
Set<Integer> values2 = Sets.newLinkedHashSet(Arrays.asList(5, 6, 7));
String key3 = "c";
Set<Integer> values3 = Sets.newLinkedHashSet(Arrays.asList(8, 9));
List<String> keys = Arrays.asList(key1, key2, key3);
Set<List<Integer>> product = Sets.cartesianProduct(values1, values2, values3);
for (List<Integer> values : product) {
for (int i = 0; i < keys.size(); ++i) {
String key = keys.get(i);
int value = values.get(i);
System.out.print(key + "=" + value + "; ");
}
System.out.println();
}