import java.util.*;
public class CarProduct{
String color;
String modelname;
String price;
public CarProduct(String c, String m, String p){
color = c;
modelname = m;
price = p;
}
}
class HashMapApplication{
public static void main(String []ar){
ArrayList<CarProduct> arraylist1 = new ArrayList<CarProduct>();
ArrayList<CarProduct> arraylist2 = new ArrayList<CarProduct>();
ArrayList<CarProduct> arraylist3 = new ArrayList<CarProduct>();
HashMap<String,ArrayList> hashmap = new HashMap<String,ArrayList>();
CarProduct Tata = new CarProduct("black","12 Lakhs","Aria");
arraylist1.add(Tata);
hashmap.put("Tata",arraylist1);
CarProduct WolksWagen = new CarProduct("off white","10 Lakhs","Passat");
arraylist2.add(WolksWagen);
hashmap.put("WolksWagen",arraylist2);
CarProduct Mahindra = new CarProduct("white","15 Lakhs","XUV");
arraylist3.add(Mahindra);
hashmap.put("Mahindra",arraylist3);
//get(int index)
//map.get(id).add(value);
//hashmap.get("")
// this contains error i dont know how iterate it because the class is there and i need access each and every field in it
for (Entry<String, ArrayList<CarProduct>> entry : hashmap.entrySet()) {
System.out.print(entry.getKey()+" | ");
for(String property : entry.getValue()){
System.out.print(property+" ");
}
System.out.println();
}
}
}
I want to extract the values from hashmap.
Please help, the key is given and the value will be arraylist.
Please help to convert the object thing in string and in displaying each and every value using get method
import java.util.*;
public class CarProduct{
String color;
String modelname;
String price;
public CarProduct(String c, String m, String p){
color = c;
modelname = m;
price = p;
}
#Override
public String toString()
{
return "Model: " + modelname + " Colour:" + color + " Price:" + price ;
}
}
class HashMapApplication{
public static void main(String []ar){
List<CarProduct> arraylist1 = new ArrayList<CarProduct>();
List<CarProduct> arraylist2 = new ArrayList<CarProduct>();
List<CarProduct> arraylist3 = new ArrayList<CarProduct>();
Map<String,List<CarProduct>> hashmap = new HashMap<String, List<CarProduct>>();
CarProduct Tata = new CarProduct("black","12 Lakhs","Aria");
arraylist1.add(Tata);
hashmap.put("Tata",arraylist1);
CarProduct WolksWagen = new CarProduct("off white","10 Lakhs","Passat");
arraylist2.add(WolksWagen);
hashmap.put("WolksWagen",arraylist2);
CarProduct Mahindra = new CarProduct("white","15 Lakhs","XUV");
arraylist3.add(Mahindra);
hashmap.put("Mahindra",arraylist3);
for (Map.Entry<String, List<CarProduct>> entry : hashmap.entrySet()) {
System.out.print(entry.getKey()+" | ");
for(CarProduct property : entry.getValue()){
System.out.print(property+" ");
}
System.out.println();
}
}
}
So there's a couple of things to correct.
Firstly the hashmap, we need to make sure the hashmap is properly typed so we've specified the type of the ArrayList otherwise we'll only be able to get Objects.
Secondly the for loop. Here we need to change the inner for loop so that it loops on CarProduct's and not Strings.
Lastly for printing the property we need to override the toString() method in CarProduct this will allow you to get the car product and put it directly in a System.out.print() as you have done.
One thing I should add is that currently you are putting the inputs into your initializer in the wrong order. Your constructor specifies color, model, price but you're using your initializer as color, price, model.
EDIT: Made the lists and maps more generic to reflect the comments on the original question
for (Map.Entry<String, ArrayList> entry : hashmap.entrySet()) {
System.out.print(entry.getKey()+" | ");
//get the arraylist first.
ArrayList<CarProduct> arrayList = entry.getValue();
for(CarProduct x: arrayList){
//display the carProduct
}
System.out.println();
}
You are basically trying to print ArrayList.toString() which will not give proper response. Try to first get the arraylist and then iterate over its contents.
Related
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
Sorry if the title is not clear, I'm not very good with programming jargon.
I have 2 string ArrayLists and an integer ArrayList obtained from one method which is passed to a separate method through the collection LinkedHashMap< String, List< String>>. However, when I try to set the integer ArrayList into a empty ArrayList declared in the receiving method, it shows the syntax error: "incompatible types: List< String> cannot be converted to List< Integer>".
Starter Method:
public static void main(String[] args) {
try{
LinkedHashMap lhm = new LinkedHashMap();
List<String> listEPC = new ArrayList<String>();
List<String> listTimeStamp = new ArrayList<String>();
List<Integer> listAntenna = new ArrayList<Integer>();
String tagID = "EQ5237";
String TimeStampStr = "12:23:22";
int tagAntenna = 2;
listEPC.add(tagID);
listTimeStamp.add(TimeStampStr);
listAntenna.add(tagAntenna);
lhm.put("epcs", listEPC);
lhm.put("timestamps", listTimeStamp);
lhm.put("antennas", listAntenna);
insertData insert = new insertData();
insert.insertData(lhm); //send map with values to new method
}catch(Exception e){
e.printStackTrace();
}
}
Receiving Method:
public class insertData {
public void insertData(LinkedHashMap<String, List<String>> readMap) {
List<String> listEPC = new ArrayList<String>();
List<String> listTimeStamp = new ArrayList<String>();
List<Integer> listAntenna = new ArrayList<Integer>();
String EPC = null;
String TimeStamp = null;
Integer Antenna = null;
listEPC = readMap.get("epcs");
listTimeStamp = readMap.get("timestamps");
listAntenna = readMap.get("antennas"); //error message here
for(int i=0; i<readMap.size(); i++){
EPC = listEPC.get(i);
TimeStamp = listTimeStamp.get(i);
Antenna = listAntenna.get(i);
System.out.println("Entry " + i );
System.out.println("Values: " + EPC + TimeStamp + Antenna);
}
}
}
This code works only if I change all instances of integers to strings, which is not what I would like in my actual code. Why is it so and how do I work around it?
You can't assign a List<String> to a List<Integer>. The elements are fundamentally different types.
You would need to construct a new List:
List<Integer> listOfIntegers = new ArrayList<>();
for (String entry : listOfStrings) {
listOfIntegers.add(Integer.valueOf(entry);
}
Of course, you also need to handle the possibility that elements of the list cannot be parsed as integers.
However, you are just throwing away type information by stuffing everything into a single map. It would be better to pass the three lists separately:
insertData(listEPC, listTimestamp, listAntenna);
and then you can have different list types in the method signature:
void insertData(
List<String> listEPC,
List<String> listTimestamp,
List<Integer> listAntenna) { ... }
I am going to include the proper answer at the bottom, but in regards to your question title, you'll have to change your method signature to:
LinkedHashmap<String, List<?>> readMap;
Then either cast the lists, which will cause an unsafe cast. eg.
List<String> listEPC = (List<String>)readMap.get("epcs");
Or cast the object.
List<?> listEPC = readMap.get("epcs");
Then in the loop cast.
EPC = (String)listEPC.get(i);
Note, these are not good solutions.
What you should have is one List that contains an object with all of the data's you need.
I can imagine the thought process went something along these lines, "I have these things, and they contain two strings and an integer. I will create a variable for each." Then you ask the question, "How do I create a collection of these things?"
The wrong answer to this question is, "I will make a list for each value, and match associated values by index." The correct answer is, "I will create a class to represent my data, and store that in a list." This is the basic essence of object orient programming (welcome to java).
First we design the class:
class EPCThing{
String EPC;
String timeStamp;
int Antennas;
public EPCThing(String tagId, String timeStamp, int antennas){
EPC=tagId;
this.timeStamp = timeStamp;
Antennas = antennas;
}
#Override
public String toString(){
return "Values: " + EPC + TimeStamp + Antenna
}
}
Now your program's main method will be something like.
List<EPCThing> things = new ArrayList<>();
String tagID = "EQ5237";
String TimeStampStr = "12:23:22";
int tagAntenna = 2;
EPCThing thing = new EPCThing(tagID, TimeStampStr, tagAntenna);
things.add(thing);
insertData insert = new insertData();
insert.insertData(things);
Then we can fix your insertData method
public void insertData(List<EPCThing> things) {
for(int i=0; i<things.size(); i++){
System.out.println("Entry " + i );
System.out.println("Values: " + things.get(i));
}
}
I am new to java, and I have this problem; I am working with a webservice from android where I send a request and I get an answer formatted like this string: 1-0,2-0,3-0,4-0,5-0,6-0,7-0,8-0,12-0,13-0 where the number before the "-" means the number of my button and the number after "-" means the button status. I split this string into an array like this:
String buttons = "1-0,2-0,3-0,4-0,5-0,6-0,7-0,8-0,13-0,14-0";
String[] totalButtons = buttons.split(",");
then I make a new request to get the status of my buttons and I get this
String status = "1-0,2-0,3-2,4-0,5-4,6-0,7-4,8-0,9-2,10-1,13-4,14-2";
String[] statusButtons = status.split(",");
The number of the buttons are going to be the same all time; in this case 10 buttons.
The problem that I have is how to compare each element of the two arrays if they can change their status every two seconds and I receive more buttons than the first time and I have to change their status with the new value. For example the first element of the array one is equal to the first element of the second array so there is no problem, but the first array does not have two elements in the second array in this case 9-2,10-1 so they should be deleted. The final result should be like this
String buttons = "1-0,2-0,3-0,4-0,5-0,6-0,7-0,8-0,13-0,14-0";
String status = "1-0,2-0,3-2,4-0,5-4,6-0,7-4,8-0,9-2,10-1,13-4,14-2";
String finalButtons = "1-0,2-0,3-2,4-0,5-4,6-0,7-4,8-0,13-4,14-2";
Here's an idea to get you started;
Map<String,String> buttonStatus = new HashMap<String,String>();
for (String button : totalButtons) {
String parts[] = button.split("-");
buttonStatus.put(parts[0], parts[1]);
}
for (String button : statusButtons) {
String parts[] = button.split("-");
if (buttonStatus.containsKey(parts[0])) {
buttonStatus.put(parts[0], parts[1]);
}
// Java 8 has a "replace" method that will change the value only if the key
// already exists; unfortunately, Android doesn't support it
}
The result will be a map whose keys are taken from the original totalButtons, and whose values will be taken from statusButtons if present. You can go through the keys and values in the Map to get the results, but they won't be in order; if you want them to be in the same order as totalButtons, go through totalButtons again and use buttonStatus.get to get each value.
The javadoc for Map is here.
I would split up each of those again and then compare those values.
ex:
String[] doubleSplit = totalButtons[index].split("-"); // "1-0" -> {"1", "0"}
import java.util.HashMap;
import java.util.Map;
/**
* #author Davide
*/
public class test {
static Map map;
public static void main(String[] args) {
// init value
String buttons = "1-0,2-0,3-0,4-0,5-4,6-0,7-0,8-0,13-0,14-0";
String[] keys = buttons.split("(-[0-9]*,*)");
init(keys);
// new value
String status = "1-0,2-0,3-2,4-0,5-4,6-0,7-4,8-0,9-2,10-1,13-4,14-2";
String[] statusButtons = status.split(",");
update(statusButtons);
print();
}
public static void init(String[] keys) {
map = new HashMap<Integer, Integer>();
for (String k : keys) {
map.put(Integer.valueOf(k), 0);
}
}
public static void update(String[] statusButtons) {
for (String state : statusButtons) {
String[] split = state.split("-");
int k = Integer.valueOf(split[0]);
int v = Integer.valueOf(split[1]);
if (map.containsKey(k)) {
map.put(k, v);
}
}
}
public static void print() {
String out = "";
for (Object k : map.keySet()) {
out += k + "-" + map.get(k) + ",";
}
System.out.println(out.substring(0, out.length() - 1));
}
}
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;
}
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
}
}