how to get key and how to add more values? [duplicate] - java

This question already has answers here:
HashMap with multiple values under the same key
(21 answers)
Closed 4 years ago.
public static void main(String[] args) {
// write your code here
LinkedHashMap<String,String>category1=new LinkedHashMap();
category1.put("action","die hard");
Scanner s=new Scanner(System.in);
String answer=s.nextLine();
if (category1.containsKey(answer))
System.out.println(category1.get("action"));
if (category1.containsValue(answer))
System.out.println(category1.keySet());
How to get the key when the user answer with it's specific value, and how to add more values to one key?

1. The map collection, does not support multiple values under the same key, it will override whatever was stored there before.
2. However, you can change it from <String,String> to <String,List<String>>, thus gaining the ability to accumulate the answers from the client into the list. The key will refer to only one object, the list of Strings, but the list itself can hold many values.
3. In order to add more Strings to the list, you will need to retrieve the list by the desired key, and then add your new String to it.
Here is some code that implements the idea:
private void test(){
Map<String, List<String>> categories = new HashMap<>();
String answerFromClient = "Some text";
List<String> actionAnswers = categories.get("action");
if (actionAnswers == null){
actionAnswers = new ArrayList<>();
actionAnswers.add(answerFromClient);
categories.put("action",actionAnswers);
}
else{
actionAnswers.add(answerFromClient);
}
}

Related

Count number of frequency of objects that have the same value [duplicate]

This question already has answers here:
How to count the number of occurrences of an element in a List
(25 answers)
Closed 1 year ago.
For example i have a list:
ArrayList<Observer> arrlist = new ArrayList<Observer>();
The list contains the observer objects
but i want to know the frequency of objects that have the same value for example String name
public class Observer{
private String name;
}
How do i do that?
You basically need to iterate over the observers and count the occurence for each key (could be just a single property or a combination depending on your needs).
Taking your example of the key just being Observer.name you could do the following:
Map<String, List<Observer>> observersByName =
arrlist.stream().collect(Collectors.groupingBy(Observer::getName));
Then iterate over the entry set and call size() on the value lists to get the frequency.
If you directly want to get the frequency, add a counting() collector:
Map<String, Long> nameFrequency = arrlist.stream().collect(
Collectors.groupingBy(Observer::getName,
Collectors.counting()));
If you want to get the frequency without using streams you could use the Map.merge() method:
Map<String, Integer> nameFrequency = new HashMap<>();
for( Observer obs : arrlist ) {
//use the name as the key, associate a value of 1 with each key
//if an entry already existed merge existing and new value by summing them
frequency.merge( obs.getName(), 1, Integer::sum);
}

Bug in HashMap / ArrayList or wrong code? [duplicate]

This question already has answers here:
ArrayList as key in HashMap
(9 answers)
Closed 6 years ago.
Tired up with trying to resolve the problem with this code:
public class MapTest {
static class T{
static class K{}
}
static Map<List<T.K>, List<String>> map = new HashMap<>();
static List<String> test(List<T.K> list, String s){
List<String> l = map.get(list);
if (l == null){
l = new ArrayList<String>();
System.out.println("New value()");
map.put(list, l);
}
l.add(s);
return l;
}
public static void main(String s[]){
ArrayList<T.K> list = new ArrayList<T.K>();
test(list, "TEST");
list.add(new T.K());
List<String> l = test(list, "TEST1");
System.out.println(l.size());
}
}
It should create a new list-value for the map only once, but output is as follows:
New value
New value
1
it is something wrong happen with hashcode of the list after I insert value in it.
I expect "new value" show up only once, and size will be 2, not 1.
is it just JVM problem or something more general?
mine one is Oracle JVM 1.8.0_65
The hashcode of the list object changes when you put an item in it. You can see how the hashcode is calculated in the ArrayList.hashCode documentation.
In general, using a mutable object as the key for a map isn't going to work well. Per the Map documentation:
Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.
Thus, when you add the list to the map a second time, the map doesn't see it as being "equal" to the first list (since it isn't according to .equals), so it adds it again.
If you want a map where keys are looked up by identity rather than by value, you can use the IdentityHashMap class.

How can I print HashMap<String, ArrayList<Integer>>? [duplicate]

This question already has answers here:
What is a raw type and why shouldn't we use it?
(16 answers)
Closed 6 years ago.
I have tried this
ScreenDumpParser dump = new ScreenDumpParser();
Map btn_bound = dump.parse();
Iterator iterator = btn_bound.keySet().iterator();
while (iterator.hasNext()) {
String key = iterator.next().toString();
List<Integer> value = btn_bound.get(key);
System.out.println(key);
}
but this line
List<Integer> value = btn_bound.get(key);
gives error:
Type mismatch: cannot convert from Object to List<Integer>
I need to print all the values along with the key in one single row.
If you want to add a value to your List you should use:
value.add( btn_bound.get(key));
and if the button is a list or something else you must add more then one value to your list with
value.addRange( btn_bound.get(key));
And if you want to get a value:
Object foo = value.get(btn_bound.get(key));

More Efficient Hash Table [duplicate]

This question already has answers here:
Multi-valued hashtable in Java
(13 answers)
Closed 7 years ago.
I'm looking to build a hash table where multiple String keys that share the same Byte array value are merged into one value with multiple keys. This is so the value isn't stored over and over again with different values. Adding a key with a value should also overwrite any existing key with the same name, but keep the value if it has a different key as well, but delete it when there is no other key.
EDIT: How do I build this data structure? For example, if I insert "hello" with a value, then add "World" with the same value, I would like the structure to something along the lines of [[Hello, World], Value] instead of [Hello, Value], [World, Value]. I tried using a list as my hashkey, but found I couldnt recall the value. Here is my code:
HashMap<List<String>, byte[]> map = new HashMap<List<String>, byte[]>();
public void storeByte (String id, int value) {
byte[] byteValue = new byte[value];
ArrayList<String> idlist = new ArrayList<String>();
idlist.add(id);
map.put(idlist, byteValue);
System.out.println(map);
}
public byte[] fetchByte(String id) {
ArrayList<String> idlistsearch = new ArrayList<String>();
idlistsearch.add(id);
byte[] output = map.get(id);
if(map.containsKey(idlistsearch)){
output = map.get(id);
} else {
return null;
}
return output;
I hope this makes sense,
Thank you.
i'm looking to build a hash table where multiple String keys that share the same Byte array value are merged into one value with multiple keys.
This is how HashMap and Hashtable works. There isn't any other option builtin.
When you define
byte[] bytes =
this is a reference, not an actual object. When you add this reference to the map, you are adding this reference and it can be added as many times as you like, but there is only one copy.
if I insert "hello" with a value, then add "World" with the same value,
You can do
byte[] bytes =
map.put("Hello", bytes);
map.put("World", bytes);
This is two keys and only one value.

Java remove duplicate objects in ArrayList [duplicate]

This question already has answers here:
How do I remove repeated elements from ArrayList?
(40 answers)
Closed 9 years ago.
I have a very lengthy ArrayList comprised of objects some of them however, are undoubtedly duplicates. What is the best way of finding and removing these duplicates. Note: I have written a boolean-returning compareObjects() method.
Example
List<Item> result = new ArrayList<Item>();
Set<String> titles = new HashSet<String>();
for( Item item : originalList ) {
if( titles.add( item.getTitle() )) {
result.add( item );
}
}
Reference
Set
Java Data Structures
You mentioned writing a compareObjects method. Actually, you should override the equals method to return true when two objects are equal.
Having said that, I would just return a new list that contains unique elements from the original:
ArrayList<T> original = ...
List<T> uniques = new ArrayList<T>();
for (T element : original) {
if (!uniques.contains(element)) {
uniques.add(element);
}
}
This only works if you override equals. See this question for more information.
Hashset will remove duplicates. Example:
Set< String > uniqueItems = new HashSet< String >();
uniqueItems.add("a");
uniqueItems.add("a");
uniqueItems.add("b");
uniqueItems.add("c");
The set "uniqueItems" will contain the following : a, b, c

Categories