The code looks like this.
public class Album {
public String currentTitle;
public HashMap<String, List<Music>> albumList = new HashMap<String, List<Music>>();
//setting the album's title
public Album(String albumTitle) {
this.currentTitle = albumTitle; //represents object's name
albumList.put(currentTitle, null);
}
//add music to album
public void addMusicToThis(Music music) {
//only if value is empty
if(albumList.get(currentTitle) == null) {
albumList.put(currentTitle, new ArrayList<Music>());
}
albumList.get(currentTitle).add(music);
}
public void printMusicList() {
}
}
and I want to print all values for the specific album, like
Album album = new Album("Test1");
Album album2 = new Album("Test2");
album.addMusicToThis(something); //this code works fine
album2.addMusicToThis(something2);
album.printMusicList(); //maybe "something"
album2.printMusicList(); //maybe "something2"
but the hashMap's values are all set to List, and I can't find the way to print the musics out.
And assume that music's name is all set.
You just get the list for a particular string, and iterate it
for(Music m : albumList.get(this.currentTitle)) {
System.out.println(m.getName());
}
It's not really clear why you're using a Hashmap, though. Your key can never change.
You must iterate over the obtained list and print the individual entries
In Java 8 you can,
albumList.get(currentTitle).forEach((music) -> System.out.println(musice.getRequiredDetails)})
You can call albumList.entrySet() which is actually iterable, traverse it and print it however you like
I think you should add the albumTitle as an argument of the printMusicList function.
For example
public void printMusicList(String albumTitle) {
List<Music> musics = albumList.get(albumTitle);
for (Music music : musics) {
System.out.println(music);
}
}
or if you want to print it all
public void printMusicList() {
Set<String> keys = albumList.keySet();
for (String key : keys) {
List<Music> musics = albumList.get(key);
for (Music music : musics) {
System.out.println(music);
}
}
}
Related
I want to add the name of array in the class to jList as below.
How can it be?
this is the method in display class
public void dataToLocal(List<XDataObject> data, XServiceType xst, XServiceOperation operation) {
if(operation.getName().equals(SNOWTAMSubscriberServiceInterface.OP_PUBLISSNOWTAM)) {
SNOWTAMPublication snowtamPublication =
(SNOWTAMPublication)data.get(0).getValue(); //This read an array with 5 values.
SNOWTAM snowtam = snowtamPublication.getSNOWTAM()[0]; //This read read the array and its contents.
jList1.add((Component) Arrays.asList((snowtamPublication.getSNOWTAM()[0]).toString())); //Here I want to add the name of Array to be as below
}
}
This is SNOWTAMPublication which is only get and set methods for array.
protected SNOWTAM[] snowtam;
public SNOWTAM[] getSNOWTAM() {
if(snowtam == null)
{
snowtam = new SNOWTAM[0];
}
return snowtam;
}
public void setSNOWTAM(SNOWTAM[] _value) {
this.snowtam = _value;
}
The picture
You could try:
<instance>.getClass().getSimpleName()
Below is the response i am getting from the server,
{
"section_id": "[24,1,5,2]"
}
and I am using GSON library
public class SectionModel {
#SerializedName("section_id")
private String mSectionId;
public String getmSectionId() {
return mSectionId;
}
public void setmProgramName(String mSectionId) {
this.mSectionId = mSectionId;
}
}
I am able to get the value "[2,18,25,26]" and store it in a String.
Now how am I supposed to get those values from String and store in an Integer arraylist.
Try this method in your code:
public ArrayList<Integer> returnArrayList(String parsetest){
ArrayList<Integer> integerArrayList= new ArrayList<>();
parsetest=parsetest.replace("[", "");
parsetest=parsetest.replace("]", "");
String[] list = parsetest.split(",");
for (String item : list) {
integerArrayList.add(Integer.valueOf(item));
}
return integerArrayList;
}
Feel free to ask any doubt in the method.
I am trying to loop through a HashMap, then for each key I want to access the object (Shipment) that is associated to the key and access my array list for further analysis purposes. Each object/key in HashMap has the same array list (metricList). I cannot seem to access it, though I have checked the private/public thing. Can someone point me in the right direction?
I think I need to maybe get the class of my object and then use the method "getList"... I tried with no luck.
This is a sample of the code (removed irrelevant parts) if it helps:
This is my object:
public class Shipment{
//Members of shipment
private final String shipment;
public Date creationDate;
public int creationTiming;
public int processingTiming;
public ArrayList<Integer> metricList;
public void createArrayList() {
// create list
metricList = new ArrayList<Integer>();
// add metric to list
metricList.add(creationTiming);
metricList.add(processingTiming);
}
public ArrayList<Integer> getList() {
return metricList;
}
}
This is the class where I create a hashMap and run through different analysis:
public class AnalysisMain {
public static Map<String, Shipment> shipMap = new HashMap();
public static void main(String[] args) {
try {
... // Different calls to analysis
}
catch {}
}
}
This is where the issue occurs (it does not recognize that I already have a "metricList", asking if I want to create local variable)
public class Metric_Analysis{
public static void analyze() throws Exception{
ResultSet rs;
try {
rs = getSQL("SELECT * FROM TEST_METRICS");
}
catch(Exception e) {
//Pass the error
throw new java.lang.Exception("DB Error: " + e.getMessage());
}
Iterator<Map.Entry<String, Shipment>> iterator = shipMap.entrySet().iterator();
while(iterator.hasNext()){
Iterator<String> metricIterator = metricList.iterator();
//Above is the Array List I want to access and loop through
//I will then perform certain checked against other values on a table...
while (metricIterator.hasNext()) {
//I will perform certain things here
}
}
}
}
You need to get the List out of your Shipment.
You can access the object from the iterator with: iterator.next();
This will also set the pointer to the next Entry in your List/Map.
Change your code:
Iterator<Map.Entry<String, Shipment>> iterator = shipMap.entrySet().iterator();
while(iterator.hasNext()){
// Get the Entry from your Map and get the value from the Entry
Entry<String, Shipment> entry = iterator.next();
List<Integer> metricList = entry.getValue().getList();
Iterator<String> metricIterator = metricList.iterator();
//Above is the Array List I want to access and loop through
//I will then perform certain checked against other values on a table...
while (metricIterator.hasNext()) {
//I will perform certain things here
}
}
Basically, i have a class where i have my arrays in, which is like this
public final class DepotDatabase {
private Driver[] arrayDrivers;
public DepotDatabase() {
arrayDrivers = new Driver[4];
arrayDrivers[0] = new Driver(1234, 1234, 0); // sample driver
arrayDrivers[1] = new Driver(4444, 4444, 0); // sample driver
arrayDrivers[2] = new Driver(1337, 1337, 1); // sample manager
arrayDrivers[3] = new Driver(1234, 1234, 0); // sample driver
}
and i want to print this array in another class, i did set up the array in another class
public Driver(int username, int password, int managerCheck) {
this.username = username;
this.password = password;
this.managerCheck = managerCheck;
}
but now i want to be able to print out all the drivers, but in another class which will be called ViewDrivers or something similar
You can create a method inside DepotDatabase to print the array, then create an object from and call print method.
public final class DepotDatabase {
private Driver[] arrayDrivers;
public void printArray() {
for (int i = 0; i < arrayDrivers.length; i++) {
Driver d = arrayDrivers[i];
System.out.println("Username : " + d.getUsername());
System.out.println("Password : " + d.getPassword());
System.out.println(" Manager Check: " + d.getManagerCheck());
}
}
the from the test class you can do:
public void execute() {
DepotDatabase ddb = new DepotDatabase();
ddb.printArray();
}
That's why you'll need to have getters and setters. You should have:
public Driver[] getDrivers() {
return arrayDrivers;
}
and in the other class, you simply call it (and print it or whatever).
Read this tutorial.
If you plan to print your array in another class you show create an accessor to it.
The common pattern for Java is to use "get plus name off attribute", getDrivers() you should also avoid the class name in such geter as it may changed due to application life.
public final class DepotDatabase {
//your code
public Driver[] getDrivers() {
return this.arrayDrivers;
}
}
Next question to answer is a returning the whole array is good idea. When you return it as above you loose control on it. And every one that call that method will be able to change the content of it.
To prevent this you should use so called Defensive copying
public Driver[] getDrivers() {
return Arrays.copyOf(arrayDrivers, arrayDrivers.length);
}
Then person will get an copy of it an will not harm your class.
The issue with this is that consumer of your class will have to call this method every time to get fresh list of cars.
To solve this issue you may want to user the [collection framework] where instead of array you cold define:
List<Driver> drivers new ArrayList<>();
and provide the drivers as [immutable] list
public Iterable<Driver> getDrivers() {
return java.util.Collections.unmodifiableList(drivers);
}
Iterable is an interface, that allow you to obtain an interator the the list consumer of class wold have possibility to traverse it. IF you wan to allow him to check that list contains some driver you can set the return type as Collection
class Storage {
private String items[] = new String[10];
public String[] getItems() {
return Arrays.copyOf(items, items.length);
}
}
class Store {
Storage storage = new Storage();
private void printStorage() {
String[] items = storage.getItems();
for (String item : items) {
}
}
}
I am using a simply city SuggestBox where I am getting list of cities from the database and putting them in GWT suggestBox oracle.
After that user can select his city from the suggestBox suggestions and user saves his record. For example, he will select "London" from the suggestbox list.
Now when user saves his record, I will not save "London" in the database for that user, instead I want to save "3" (london ID) in database.
For this what I am doing is like this:
public MultiWordSuggestOracle createCitiesOracle(ArrayList<City> cities){
for(int i=0; i<cities.size(); i++){
oracle.add(cities.get(i).getCity()+","+cities.get(i).getCityId());
}
return oracle;
}
Now, I have the city and cityID both displaying in suggestBox and then can save from there 'city' and 'cityId'.
Everything works fine, but it doesn't looks good:
like it dispays as "London,3" and so on in the suggestBox suggestions..
I don't want to show this 3, how and where can I save this Id(3) for future use?
You can also create your own typed Suggestion-Box. You need to implement "Suggestion" and extend "SuggestOracle".
Super simple version may look:
// CityOracle
public class CityOracle extends SuggestOracle {
Collection<CitySuggestion> collection;
public CityOracle(Collection<CitySuggestion> collection) {
this.collection = collection;
}
#Override
public void requestSuggestions(Request request, Callback callback) {
final Response response = new Response();
response.setSuggestions(collection);
callback.onSuggestionsReady(request, response);
}
}
//CitySuggestion
public class CitySuggestion implements Suggestion, Serializable, IsSerializable {
City value;
public CitySuggestion(City value) {
this.value = value;
}
#Override
public String getDisplayString() {
return value.getName();
}
#Override
public String getReplacementString() {
return value.getName();
}
public City getCity() {
return value;
}
}
// Usage in your code:
// list of cities - you may take it from the server
List<City> cities = new ArrayList<City>();
cities.add(new City(1l, "London"));
cities.add(new City(2l, "Berlin"));
cities.add(new City(3l, "Cracow"));
// revert cities into city-suggestions
Collection<CitySuggestion> citySuggestions = new ArrayList<CitySuggestion>();
for (City city : cities) {
citySuggestions.add(new CitySuggestion(city));
}
//initialize city-oracle
CityOracle oracle = new CityOracle(citySuggestions);
// create suggestbox providing city-oracle
SuggestBox citySuggest = new SuggestBox(oracle);
// now when selecting an element from the list, the CitySuggest object will be returned. This object contains not only a string value but also represents selected city
citySuggest.addSelectionHandler(new SelectionHandler<SuggestOracle.Suggestion>() {
#Override
public void onSelection(SelectionEvent<Suggestion> event) {
Suggestion selectedItem = event.getSelectedItem();
//cast returned suggestion
CitySuggestion selectedCitySuggestion = (CitySuggestion) selectedItem;
City city = selectedCitySuggestion.getCity();
Long id = city.getId();
}
});
Keep the reference from city name to id in a Map<String, Integer> and then look the ID up there before you save it.