How to print an entire dictionary.put entry? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 days ago.
Improve this question
I am trying to get this code to print out both the "hello" and the "there" from the dictionary. Currently it only prints out the "there". Is there a way to print out both of these?
import java.lang.*;
import java.util.*;
import java.io.*;
public class Task
{
public static void main (String[] args)
{
Scanner scan = new Scanner(System.in);
Dictionary dictionary = new Hashtable();
dictionary.put("hello", "there");
I tried to just do
System.out.println(i.nextElement());
I thought it would print out the entire dictionary entry
but all that did was print out the "there"

You can get the first element of the entrySet from the Map using its Iterator. However, you should use LinkedHashMap which maintains insertion order, if you want the result to be meaningful.
Map<String, String> map = new LinkedHashMap<>();
map.put("hello", "there");
System.out.println(map.entrySet().iterator().next());

You have not shown how you are iterating the Dictionary. I would change from that to a Map, and you should not use raw-types. Once you have a Map you can iterate the entrySet to get both keys and values. Like,
Map<String, String> dictionary = new HashMap<>();
dictionary.put("hello", "there");
for (Map.Entry<String, String> i : dictionary.entrySet()) {
System.out.printf("key = %s, value = %s%n", i.getKey(), i.getValue());
}
Which outputs
key = hello, value = there

Related

Refactor this code snippet [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I am unable to refactor and make this snippet cleaner and smaller.
For example i want to add a new value to the listOfValues in one line, instead of first initliazing it to an empty arraylist then calling add on it on a seperate line and finally putting listofvalues in the hasmap on the third line. Also in the else statement is the hasMap.put necessary since we are getting a reference to listOfValues and if we add something to it hashMap will contain it automatically?
MyObject:
key: String
values: List<Value>
Value:
Value1: String
Value2: String
HashMap<String, MyObject> hashMap = new HashMap<>();
List<Value> listOfvalues;
if (!hashMap.containsKey(key)) {
listOfvalues = new ArrayList<>();
listOfvalues.add(Value.builder().withValue1(Value1).withValue2(Value2).build());
hashMap.put(key, MyObject.builder().withkey(key).withvalues(listOfvalues).build());
} else {
listOfvalues = hashMap.get(key).getvalues();
log.info(String.format("Duplicate key: %s. Previous Value(s): %s", key,
listOfvalues));
listOfvalues.add(Value.builder().withValue1(Value1).withValue2(Value2).build());
hashMap.put(key, MyObject.builder().withkey(key).withvalues(listOfvalues).build());
}
The common part with list and map working can be moved out from if/else:
Map<String, MyObject> hashMap = new HashMap<>();
List<Value> listOfvalues;
if (!hashMap.containsKey(key)) {
listOfvalues = new ArrayList<>();
} else {
listOfvalues = hashMap.get(key).getvalues();
log.info(String.format("Duplicate key: %s. Previous Value(s): %s", key, listOfvalues));
}
listOfvalues.add(Value.builder().withValue1(Value1).withValue2(Value2).build());
hashMap.put(key, MyObject.builder().withkey(key).withvalues(listOfvalues).build());

#java HashMap and input [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I have a problem with imput some values in a hashmap,
the HashMap<String, ArrayList<Integer>> must contain the name and the relative points.I'm not able to put more values for a key.
The input file is the following.
Marco,Matteo,Luca,Giovanni;34,35,3,35
Marco,Anna,Chiara;1,5,6
A map doesn't accept duplicate keys.
You could switch to using either a list of maps (One map per row):
List<Map<String, Integer>> records = ...
Map<String, Integer> map1 = new HashMap<>(),
map2 = new HashMap<>();
map1.put("Marco", 34);
map1.put("Matteo",35);
//put values for Luca,Giovanni...
records.add(map1);
//create and add maps for other rows
OR a map of lists/arrays (one list per column)
Map<String, List<Integer>> map1 = new HashMap<>()
List<Integer> marco = ...
marco.add(34);
marco.add(1);
map1.put("Marco", marco);
//do the same for other records...

For-loop Hashmap Java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Im trying to loop a Hashmap from a certain starting point. My code for now is:
for (object o : objects.values()) {
code in here
}
But now im wondering how i can start the loop at a certain key or value?
You can create a "view" that starts and ends with certain keys by using a SortedMap implementation like TreeMap instead of a HashMap. (You can also simply start at a certain key and process the remainder, without specifying an ending key, by using tailMap().)
SortedMap<String, Article> encyclopaedia = new TreeMap<>();
/* Populate the map. */
...
for (Article val : cyc.subMap("Sonar", "Tax Law").values()) {
/* Process only Volume 17. */
}
Note that this will actually exclude "Tax Law" from processing, as the bounds of the sub-map are a half-open interval. If you need to handle cases like that, you can use the further specialization, NavigableMap (which is also implemented by TreeMap).
you can use the entrySet of the Collections and iterate over it...
Example:
public static void main(String[] args) {
Map<Integer, String> myMap = new HashMap<Integer, String>();
for (Entry<Integer, String> entry : myMap.entrySet()) {
System.out.println("The key is:" + entry.getKey());
System.out.println("The value is:" + entry.getValue());
}
}

i want to get the keys and values of each set using java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Am new to java i have formed a set of result in
`Map<String, Map<String, List<String>>>`
now i want to get the keys and values of each set
How should get this. anyone please suggest me
thanks in advance.
You will want to look at the documentation for Maps.
myArbitrarilyNamedMap = new Map<String, Map<String, List<String>>>();
//do stuff so that myArbitrarilyNamedMap contains values
Set firstLevelKeys = myArbitrarilyNamedMap.keySet(); //this bit
For me is much easier to study with examples. I can give you a little example. May be it will be usefull.
public class MapHierarchy {
public static void main(String[] args) {
// preparation
Map<String, Map<String, List<String>>> myTestMap = new HashMap<>();
ArrayList<String> listOfValues = new ArrayList<>();
listOfValues.add("Hello");
listOfValues.add("my");
listOfValues.add("little");
listOfValues.add("friend");
HashMap<String, List<String>> innerMap = new HashMap<>();
innerMap.putIfAbsent("innerMapKey", listOfValues);
myTestMap.put("outerKey", innerMap);
// where the magic happens
System.out.println("Keys of outer map: " + myTestMap.keySet().toString());
for (Map.Entry<String, List<String>> innerMapItem : innerMap.entrySet()) {
String innerMapItemKey = innerMapItem.getKey();
System.out.println("Key of inner map: " + innerMapItemKey);
System.out.println("Values of inner map: " + innerMapItem.getValue().toString());
}
}}

How do I declare multi-dimensional arrays or structures in Java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have this structure in PHP and I'm not really sure how to translate it into Java, I need to mention that all keys and values are strings.
For bonus points, please show an example
private $group = array(
"group1" = array("item1","item2"),
"group2" = array("item3","item4"),
....
"groupn" = array("itemn","itemn+1"),
....
);
Map<String, List<String>> group = new LinkedHashMap<String, List<String>>();
group.put("group1", new ArrayList<String>(Arrays.asList("item1", "item2")));
group.put("group2", new ArrayList<String>(Arrays.asList("item3", "item4")));
In php, if you iterate over the elements with a foreach
foreach ($group as $key => $subarray)
You're guaranteed the first $key is 'group1' because a php array is implicitly order by key creation time. If you want the same guarantee in java you must use LinkedHashMap. Otherwise a regular HashMap is fine.
An array in PHP is actually an ordered map. A map is a type that
associates values to keys. Source
Java uses the true definition of an array. What you want is a Map.
Use a Map<String, Collection<String>>. If values in the collection are unique, use a Set, otherwise a List.
You can use a Map as your solution :
Map<String, List<String>> map = new HashMap<String, List<String>>();
map.put("group1", Arrays.asList("item1", "item2", "item3");
etc...
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
map.add("group1", list);
And so on...

Categories