Read objects content from hashmaps - java

I need to save pairs (string,object) into a hashmap. Basically I managed to populate the hashmap but I don't know how to access the values stored into memory.
This is my code:
HashMap<String, speedDial> SDs = new HashMap<String, speedDial>();
speedDial sd = new speedDial();
SDs.put(String.valueOf(temp),sd); whre temp is my index and sd my object
Then I fill in data into the sd reading them from an xml file.
When I debug the project with eclypse I can see the values are stored correctly into memory, but I've no idea how to retrive the string values associated to the object, see below the SD object format
class speedDial{
String label, dirN;
speedDial (String l, String dN) {
this.label = l;
this.dirN = dN;
}
}
See the picture below: it highlights the data I'm trying to access!
enter image description here
When I try to access the hashmap and print it's values I only got the last one, I use the following:
for ( int k = 0; k <50; k++) {
speedDial.printSD(SDs.get(String.valueOf(k)));
}
This is my printSD method taken from the speedDial class:
public static void printSD (speedDial SD) {
System.out.println("Dir.N: " + SD.dirN + " Label: " + SD.label);
}
And this is the output for all the 50 iterations, that is the last element I added to the hashmap in another for cycle that reads from a xml file.
Dir.N: 123450 Label: label5

Given a HashMap such as:
SpeedDial speedDial1 = new SpeedDial("test1", "test2");
SpeedDial speedDial2 = new SpeedDial("test3", "test4");
SpeedDial speedDial3 = new SpeedDial("test5", "test6");
HashMap<String, SpeedDial> exampleHashMap = new HashMap<>(3);
exampleHashMap.put("key1", speedDial1);
exampleHashMap.put("key2", speedDial2);
exampleHashMap.put("key3", speedDial3);
You can retrieve the value for a given key like so:
SpeedDial exampleOfGetValue = exampleHashMap.get("key1");
System.out.println(exampleOfGetValue.label);
System.out.println(exampleOfGetValue.dirN);
This outputs:
test1
test2
If you want to retrieve the keys for a given value then you could use something like:
public final <S, T> List<S> getKeysForValue(final HashMap<S, T> hashMap, final T value) {
return hashMap.entrySet()
.stream()
.filter(entry -> entry.getValue().equals(value))
.map(Map.Entry::getKey)
.collect(Collectors.toList());
}
If you call this function like so:
List<String> exampleOfGetKeys = getKeysForValue(exampleHashMap, speedDial1);
System.out.println(exampleOfGetKeys);
It would output a list of all keys that have this value:
[key1]

The following code will iterate through the map and will store the key and values in two lists.
List<String> keys = new ArrayList();
List<Object> values = new ArrayList();
for (Map.Entry<String, Object> speedDial: SDs.entrySet()) {
Object speedDialValue = speedDial.getValue();
String key= speedDial.getKey();
keys.add(key);
values.add(speedDialValue);
}
To retrieve the String value, typically getters are used as it is recommended to use the private modifier for your class attributes.
public class speedDial{
private String label, dirN;
public speedDial (String l, String dN) {
this.label = l;
this.dirN = dN;
}
public String getLabel(){
return this.label;
}
public String getDirN(){
return this.dirN;
}
}
The you can simply use yourObject.getLabel(); or yourObject.getDirN();
Hope that helps!

SDs.keySet() Gives you the Set of the keys of your HashMap
You can have the list of values using
for (String mapKey : SDs.keySet()) {
System.out.println("key: "+mapKey+" value: "+ SDs.get(mapKey).toString());
}
Yous have to write a toString() fonction for your speedDial

Related

Sum value Of Class Objects Property In ArrayList

I have an ArrayList which having many objects. I want to do sum of values of the same property name.
Examples Data in Array List which is Objects of ProfitAndLossDataDO
"Michel" , 5000
"Alex" , 5000
"Edvin" , 4000
"Sosha" , 3000
"Michel" , 2000
"Alex" , 3000
And the Result Would be (Sum of values when person are same)-
"Michel" ,7000
"Alex" , 8000
"Edvin" , 4000
"Sosha" , 3000
The Logic class ProfitAndLossDataDO
public class ProfitAndLossDataDO {
String ledgerName;
double ledgerAmount;
public ProfitAndLossDataDO() {
}
public ProfitAndLossDataDO(String ledgerName, double ledgerAmount) {
this.ledgerName = ledgerName;
this.ledgerAmount = ledgerAmount;
}
public String getLedgerName() {
return ledgerName;
}
public void setLedgerName(String ledgerName) {
this.ledgerName = ledgerName;
}
public double getLedgerAmount() {
return ledgerAmount;
}
public void setLedgerAmount(double ledgerAmount) {
this.ledgerAmount = ledgerAmount;
}
#Override
public String toString()
{
return ("ledger name : "+this.getLedgerName()+" Amount : "+this.getLedgerAmount());
}
}
Thanks
I'd iterate the list and collect the results in a map:
public static List<ProfitAndLossDataDO> sumPerLedgerName
(List<ProfitAndLossDataDO> list) {
Map<String, ProfitAndLossDataDO> map = new HashMap<>();
for (ProfitAndLossDataDO p : list) {
String name = p.getLedgerName();
ProfitAndLossDataDO sum = map.get(name);
if (sum == null) {
sum = new ProfitAndLossDataDO(name, 0.0);
map.put(name, sum);
}
sum.setLedgerAmount(sum.getLedgerAmount() + p.getLedgerAmount());
}
return new ArrayList<>(map.values());
}
EDIT:
Java 8's enhancements to the Map interface allow us to implement this method in a slightly more elegant way, with the annoying if block in the middle:
public static List<ProfitAndLossDataDO> sumPerLedgerName
(List<ProfitAndLossDataDO> list) {
Map<String, ProfitAndLossDataDO> map = new HashMap<>();
for (ProfitAndLossDataDO p : list) {
String name = p.getLedgerName();
ProfitAndLossDataDO sum = map.computeIfAbsent(name, n -> new ProfitAndLossDataDO(n, 0.0));
sum.setLedgerAmount(sum.getLedgerAmount() + p.getLedgerAmount());
}
return new ArrayList<>(map.values());
}
You can use a Hash Map as aleroot suggested. Use name as the key and sum as the value. Whenever you need to insert value just check such entry exists with the same key and update it.
public class ProfitAndLossDataDO {
HashMap<String, Double> data = new HashMap<String, Double>();
public ProfitAndLossDataDO() {
}
public void updateLedger(String ledgerName, double ledgerAmount) {
double temp;
if(data.containsKey(ledgerName)) {
temp = data.get(ledgerName)+ledgerAmount;
data.put(ledgerName,temp);
}
else {
data.put(ledgerName,ledgerAmount);
}
}
}
Why you don't just put them in an Map based collection with key/value pairs ?
I think that in this case a Map based collection is more suitable, for the data you have and the context in which you want to use it.
If you need to preserve the single items inside the list, you could use a linked list as Value of the map .
For example :
HashMap<String, LinkedList<Double>> cache = new HashMap<String, LinkedList<Double>>();
and SUM each element of the value LinkedList to find the total amount ... You could even wrap the LinkedList of doubles into a container object with helper functions like getTotal() or Sum().

How to get value from TreeMap in Java?

My problem is can't get an object "Item" (value) from my Treemap. I need send that info to my GUI class and display it in JList to get a select list, so can easily select and add songs to playlist, but only what I get as an output is "01, 02, 03, 04, 05" (key). Please help, because I'm beginner and have no idea what to do.
public class LibraryData {
private static class Item {
Item(String n, String a, int r) {
name = n;
artist = a;
rating = r;
}
// instance variables
private String name;
private String artist;
private int rating;
private int playCount;
public String toString() {
return name + " - " + artist;
}
}
private static Map<String, Item> library = new TreeMap<String, Item>();
static {
library.put("01", new Item("How much is that doggy in the window", "Zee-J", 3));
library.put("02", new Item("Exotic", "Maradonna", 5));
library.put("03", new Item("I'm dreaming of a white Christmas", "Ludwig van Beethoven", 2));
library.put("04", new Item("Pastoral Symphony", "Cayley Minnow", 1));
library.put("05", new Item("Anarchy in the UK", "The Kings Singers", 0));
}
public static String[] getLibrary() {
String [] tempa = (String[]) library.keySet().toArray(new String[library.size()]);
return tempa;
}
SOLUTION:
Because I've to pass the values to another class:
JList tracks = new JList(LibraryData.getLibrary());
I made something like that and it's works
public static Object[] getLibrary() {
Collection c = library.values();
return c.toArray(new Item[0]);
Thank You guys, after 10 hours I finally done it!
}
With this code that you have:
String [] tempa = (String[]) library.keySet().toArray(new String[library.size()]);
You are getting all keys from the map. If you want all values, then use:
library.values();
Finally, if you need to get a value by key use V get(Object key):
library.get("01");
Which will return you the first Item from the map.
It's not very clear which one of these you want, but basically these are the options.
** EDIT **
Since you want all values you can do this:
library.values().toArray()
JList expects an array or vector of Object so this should work.
If you want to get value and key by position, you can use:
key: library.keySet().toArray()[0]
value: library.get(key);
OR (if you just want value)
library.values().toArray()[0];
You can use the ArrayList:
1 - The best for flexible-array managing in Java is using ArrayLists
2 - ArrayLists are easy to add, get, remove and more from and to.
3 - Treemaps are a little... arbitrary. What I say is that if you use the get(Object o) method from a Treemap, the Object o must be a key, which is something not very flexible.
If you want them, use this code:
import java.util.ArrayList;
import com.example.Something; // It can be ANYTHING
//...
ArrayList<Something> somethingList = new ArrayList<Something>();
//...
somethingList.add(new Something("string", 1, 2.5, true));
//...
boolean isSomething = somethingList.get(somethingList.size() - 1); // Gets last item added
//...
int listSize = somethingList.size();
//...
somethingList.remove(somethingList.size() - 1); // Removes last item and decrements size
//...
Something[] nativeArray = somethingList.toArray(new Something[somethingList.size()]); // The parameter is needed or everthing will point to null
// Other things...
Or the classic Treemap:
Object keyAtIndex0 = library.keySet.toArray(new Object[library.size()])[0];
Object value = library.get(keyAtIndex0);
Good Luck!
I was returning a list of string values as treemap value. The used approach is
private Map<String, TreeSet<String>> result;
TreeSet<String> names= result.get(key);
for(String contactName: names){
print contactName;
}

storing multiple values in a map against single key

I have the following file named ght.txt in my c: and it contains the following data
Id|ytr|yts
1|W|T
2|W|T
3|W|T
Now the thing is that positions of this columns (Id|ytr|yts) is also not in order means they can be reshuffled also..for ex
Id|ytr|dgfj|fhfjk|fgrt|yts
or they can be as ..
Id|wer|ytr|weg|yts
so I have done the following way and read them in java as shown below
String[] headers = firstLine.split("|");
int id, Ix, Ixt, count = 0;
for(String header : headers) {
if(header.equals("Id")) {
idIx = count;
}elseif (header.equals("Ix")) {
Ixt = count;
} elseif (header.equals("Ixt")) {
Ixt = count;
}
count++;
}
Now I need to store them in a map in such a way that against id I will get the value of column ytr and yts so in map there should be single key but against that key value could be multiple please advise how to store in map in such a way
Using a Map<Integer,List<String>> sounds like a viable first approach.
As it sound like your value is structured, it might be even better to create a value class to hold this, eg. Map<Integer, YourValueClass> where
class YourValueClass
{
String ix;
String ixt;
// constructor, getters and setters
}
Basically, you should think in terms of classes/objects - don't be in object denial :-)
Cheers,
I'm not quite sure what you mean, but if I get it right, you are looking for a multimap.
You can roll one yourself, as #Anders R. Bystrup suggests.
Or you can use an existing implementation like the Google Collections Multimap.
Don't store one key and multiple values. Instead, you can store a Key and Values as a List.
You can use MultiMap from Guava Library:
MultiMap<String,String> map = ArrayListMultimap.create();
map.put("key","value1");
map.put("key","value2");
By using:
System.out.println(map.get("key");
Prints:
["value1","value2"]
Value Class
class TextValues {
final int id;
final String ix;
final String ixt;
private TextValues(final int id, final String ix, final String ixt){
this.id = id;
this.ix = ix;
this.ixt = ixt;
}
public static TextValues createTextValues(int id, String ix, String ixt) {
return new TextValues(id, ix, ixt);
}
}
Usage:
Map<Integer, TextValues> map = new HashMap<Integer, TextValues>();
map.put(1, TextValues.createTextValues(1, "ix value ", "ixt value"));
public static void main(String[] args) {
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> valSetOne = new ArrayList<String>();
valSetOne.add("ABC");
valSetOne.add("BCD");
valSetOne.add("DEF");
List<String> valSetTwo = new ArrayList<String>();
valSetTwo.add("CBA");
valSetTwo.add("DCB");
map.put("FirstKey", valSetOne);
map.put("SecondKey", valSetTwo);
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
String key = entry.getKey();
List<String> values = entry.getValue();
System.out.println("Value of " + key + " is " + values);
}
}
You can use Set or List based on your requirement i.e you need elements in ordered or unordered collection.This is a simple method of having single key with multiple values.

Android: Find a value inside an Array with a "a like" value

I'm having problem with this part
My Code:
String[] sample = {'name=NAME', 'add=ADD', 'age=AGE', 'gender=GENDER'};
for(int a = 0; a < sample.length; a++) {
if(Arrays.asList(sample).contains("name")) {
Log.d(tag, "successful");
} else {
Log.d(tag, "failed");
}
}
When I'm using this code, it doesn't return true, but when I use .contains("name=NAME")
it returns true.
Is there any possibility to compare a string value using not too specific string?
BTW, those string values came from a file.txt.
If you use Arrays.asList(sample) you will have a list containing the String "name=NAME" hence it doesn't contain the String "name"
You should loop over the array (not needed to create the list)
boolean found = false;
for (String s: sample)
if (s.contains("name"))
found=true;
To get a value based on key:
1) You can use HashMap object
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main(String args[]) {
// create hash map
HashMap newmap = new HashMap();
// populate hash map
newmap.put("name", "abcde");
newmap.put("age", "XX");
newmap.put("Gender", "Male");
// get value of key Gender
String val=(String)newmap.get("Gender");
// check the value
System.out.println("Value for key 3 is: " + val);
}
}
2) You can also use Map object
Map<String, String> map = new HashMap<String, String>();
map.put("name", "abcde");
map.put("age", "XX");
String val=(String)map.get("name");
3) You can also use two dimentional array of string
String data = "name=Name,age=Age";
String[] rows = data.split(",");
String[][] matrix = new String[rows.length][];
int r = 0;
for (String row : rows) {
matrix[r++] = row.split("\\=");
}
System.out.println(matrix[1][1]);
.contains method will check whether the object is present in the ArrayList or not.
Here in your case objects are : "name=NAME","add=ADD","age=AGE", "gender=GENDER" which are of String type. So it is obvious that it returns false.
For you, better practice is to create a class named Person which has attributes like name,add,age and gender. Then store the object of it in ArrayList and you can check whether object is in ArrayList of not using .contains() function. Like below :
class Person{
String name;
String add;
int age;
String gen;
// All getters and setters methods will be here.
}
public static void main(String[] args){
Person p = new Person();
//Here you can set the properties of person using p.setXXX() methods
//Now suppose you have ArrayList of Person object named "per" then you can check
// whether Person exist in it or not using contains like below
per.contains(p) //returns true if per contains object p
//or you can check name by below code
for(Person temp:per){
if(temp.getName().equals(name)){ //returns true if name matchs with Persons name
//do something
}
}

Duplicate elements in ArrayList

I have two array list, One is to save name and other is to save quantity. I want to avoid duplicate in the array list. Name array list contains name and its corresponding quantity is contained in quantity array list.
My array list can contains duplicate names, I want to traverse array list to check the name if already exists, if it exists then add the quantity to the previous value and delete duplicate entry.
Eg
Name Quantity
ABC 20
xyz 10
ABC 15
Output Required
Name Quantity
ABC 35
XYZ 10
Thanks
You should use a Map instead, which will not allow for duplicate entries. You use it something like this:
Map<String, Integer> nameToQuantityMap = new HashMap<String, Integer>():
nameToQuantityMap.put("Mr Smith", 100);
nameToQuantityMap.put("Mrs Jones", 500);
EDIT: Now that you've edited the question, the answer is different. If you want to add the values of duplicate keys, you'll have to do something like this:
// For each (name, quantity) pair
if (nameToQuantityMap.containsKey(name) ) {
Integer sum = nameToQuantityMap.get(name) + quantity;
nameToQuantityMap.put(name, sum);
}
else {
nameToQuantityMap.put(name, quantity);
}
I want to avoid duplicate in the array list.
In that case use HashSet
Or else if you have 2 parallel ArrayList then you can use HashMap
The structure you attempt to represent resembles something that should be represented by a Map, which is a key -> value storage type of structure. Having two lists and trying to keep the in sync is a bad idea.
Use java.util.Map where key would be you map and value would be value.
Map<String,Integer> map = new HashMap<>();
if(map.get(name)!=null){
Integer oValue = map.get(name)+nNalue;
}else
map.put(name,value);
Try this if you want to add value to the previous value if Key already exists .
public class Example {
static Map<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) {
insertNameAndQuantity("A", 10);
insertNameAndQuantity("B", 25);
insertNameAndQuantity("A", 25);
System.out.println(map);
}
public static void insertNameAndQuantity(String key, Integer value) {
Integer count = map.get(key);
if (count == null)
map.put(key, value);
else
map.put(key, count + value);
}
}
Output:
{A=35, B=25}
this is an example implement on c# code.
public class temp
{
[Test]
public void T()
{
var list1 = new ArrayList(){"ABC", "xyz", "ABC"};
var list2 = new ArrayList() {20, 10, 15};
var nameList = new List<string>();
var list1result = new ArrayList();
var list2result = new ArrayList();
int index = 0;
foreach (string name in list1)
{
if (!nameList.Contains(name))
{
list1result.Add(name);
var quantity = list2[index] ?? 0;
list2result.Add(quantity);
nameList.Add(name);
}
else
{
var index2 = 0;
foreach (string name2 in list1result)
{
if (name2 == name)
{
list2result[index2] = (int)list2result[index2] + (int)list2[index];
}
index2++;
}
}
index++;
}
Assert.True(list1result.Count == 2, list1result.Count + " t1");
}
}
I've tested the output, it's correct.

Categories