add array into array - java

I have data of tracks & tracklinks like folowing:
trackname - abc
links - www.abc.com
www.abc1.com
www.abc2.com
trackname - xyz
links - www.xyz.com
www.xyz1.com
www.xyz2.com
I want to make array with in array in Java. so final array would be:
trackdata = {
[0] {
[trackname] = 'abc',
[tracklinks] = {
[0] = "www.abc.com";
[1] = "www.abc1.com";
[2] = "www.abc2.com";
}
},
[1] {
[trackname] = 'xyz',
[tracklinks] = {
[0] = "www.xyz.com";
[1] = "www.xyz1.com";
[2] = "www.xyz2.com";
}
}
I have tried to make this using ArrayList, Map but not succeed.
Map<String,String> map = new HashMap<>();
map.put("trackname", "abc");
ArrayList<String> myLinks= new ArrayList<>();
myLinks.add("www.abc.com");
myLinks.add("www.abc1.com");
myLinks.add("www.abc2.com");
map.put("tracklinks", myLinks);
please help me here.

Consider using a multimap, a map whose values are list objects:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Starter {
public static void main(String[] args) {
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> myLinks= new ArrayList<>();
myLinks.add("www.abc.com");
myLinks.add("www.abc1.com");
myLinks.add("www.abc2.com");
map.put("abc", myLinks);
System.out.println(map); // {abc=[www.abc.com, www.abc1.com, www.abc2.com]}
}
}

You should create a class and then access the properties like you want.
class TrackData {
private String trackme;
private List<String> trackLink;
public String getTrackme() {return trackme;}
public void setTrackme(String trackme) {this.trackme = trackme;}
public List<String> getTrackLink() {return trackLink;}
public void setTrackLink(List<String> trackLink) {this.trackLink = trackLink;}
}
To access it:
#Test
void arrayInArray_Test1() {
List<TrackData> trackData = new ArrayList<>();
trackData.add(new TrackData(){{
setTrackme("abc");
setTrackLink(new ArrayList<String>(){{
add("www.abc.com");
add("www.abc1.com");
add("www.abc2.com");
}});
}});
trackData.add(new TrackData(){{
setTrackme("xyz");
setTrackLink(new ArrayList<String>(){{
add("www.xyz.com");
add("www.xyz1.com");
add("www.xyz2.com");
}});
}});
System.out.println(trackData);
}
If you are using a newer Java version, you can create a record instead of a class.

You can achieve as follows
public class TrackTest {
public static void main(String[] args) {
List<Tracks> trackList = new ArrayList<>();
Tracks track1 = new Tracks("abc");
track1.getTrackLinks().add("www.abc.com");
track1.getTrackLinks().add("www.abc1.com");
track1.getTrackLinks().add("www.abc2.com");
Tracks track2 = new Tracks("xyz");
track2.getTrackLinks().add("www.xyz.com");
track2.getTrackLinks().add("www.xyz1.com");
track2.getTrackLinks().add("www.xyz2.com");
trackList.add(track1);
trackList.add(track2);
System.out.println(trackList);
}
static class Tracks{
private String trackName;
private List<String> trackLinks;
public Tracks(String trackName) {
this.trackName = trackName;
this.trackLinks = new ArrayList<>();
}
public Tracks(String trackName, List<String> trackLinks) {
this.trackName = trackName;
this.trackLinks = trackLinks;
}
public String getTrackName() {
return trackName;
}
public List<String> getTrackLinks() {
return trackLinks;
}
#Override
public String toString() {
return "Tracks [trackName=" + trackName + ", trackLinks=" + trackLinks + "]";
}
}
}
Let me know, if you want other approach.

how are u?
Why u dont do this.
Create class named URL, for example.
public class Url(){
//atributes
String domain;
String url;
//Contructor
public class URL(String domain, String url){
this.domain = domain;
this.url = url;
}
}
In ur main.class, u can create one Arraylist to saves ur instaces of URL.
public static void newURL(){
String domain, url;
Scanner keyboard = new Scanner(System.in);
//ask domain, i will use an example.
System.out.println("What is domain of URL?");
domain = keyboard.nextLine();
System.out.println("What is url?");
url = keyboard.nextLine;
//now, u have atributes of new url
URL url = new URL(domain,url);
}
What its ur objective? It's important question.
If is for simple control in a little program, u can do this

Related

.contains() problem/looks like it doesnt work

I'm working on web scraper and I can't solve problem I'm having for the second day in row.
The problem with this method is when the bot is supposed to visit the website, harvest all URL's, and add the ones of them it didn't visit already to List< String> "toVisit"
Problematic code:
Elements temp = userAgent.visit(currentUrl).findEvery("<a href>");
for (Element e : temp) {
String x = e.getAt("href");
if(!visited.contains(x)) {
toVisit.add(x);
}
}
However, the if statement doesn't filter (or filter it in way I didn't find out) url's and I have no idea why.
I tried delete the "!" in the statement and create an else part and paste toVisit.add(x) there, but it didn't help.
When I print every url, the bot visits the same ones two or even five times.
EDIT (visited defined)
static List<String> visited = new ArrayList<String>();
EDIT2 (whole code)
import java.util.ArrayList;
import java.util.List;
import com.jaunt.*;
public class b03 {
static String currentUrl = "https://stackoverflow.com";
static String stayAt = currentUrl;
static String searchingTerm = "";
static int toSearch = 50;
static List<String> toVisit = new ArrayList<String>();
static List<String> visited = new ArrayList<String>();
static UserAgent userAgent = new UserAgent();
public static void main(String[] args) {
System.out.println("*started searching...*");
while(visited.size() < toSearch)
visitUrl(currentUrl);
System.out.println("\n\n*done*\n\n");
}
public static void visitUrl(String url) {
visited.add(url);
evaluateUrls();
searchTerm();
toVisit.remove(0);
currentUrl = toVisit.get(0);
}
public static void searchTerm() {
//if(userAgent.doc.getTextContent().contains(searchingTerm))
System.out.println(visited.size() +") "+ currentUrl);
}
public static void evaluateUrls() {
try {
Elements temp = userAgent.visit(currentUrl).findEvery("<a href>");
for (Element e : temp) {
String x = e.getAt("href");
if(!visited.contains(x) && x.contains(stayAt)) {
toVisit.add(x);
}
}
}catch (Exception e) {
System.out.println(e);
}
}
}
Your bot visits the some urls several times because you add them several times to the toVisit list.
To illustrate this: let's assume that the first few links that your bot find on the stackoverflow site are the links to "home" (stackoverflow.com), tags (stackoverflow.com/tags), users (stackoverflow.com/users) and jobs (stackoverflow.jobs) and your bot adds three of those to the toVisit list.
Next it visits the tags page (stackoverflow.com/tags). This page contains again links to the same four urls as before. Since you didn't yet visit the users and the jobs subpage it will add those a second time to the toVisit list.
To fix this, you should only add urls to the toVisit list that are not in the visited list and not in the toVisit list:
if (!visited.contains(x) && !toVisit.contains(x) && x.contains(stayAt)) {
toVisit.add(x);
}
I can not try this code because of the jaunt lib
Split your code, make it readable.
Dont use "static" as much as possible.
Hope it helps
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import com.jaunt.*;
public class B03 {
static String currentUrl = "https://stackoverflow.com";
static String stayAt = currentUrl;
static String searchingTerm = "";
static int toSearch = 50;
static List<String> toVisit = new ArrayList<String>();
static List<String> visited = new ArrayList<String>();
static UserAgent userAgent = new UserAgent();
public static void main(String[] args) {
System.out.println("*started searching...*");
toVisit.add(currentUrl);
while(toVisit.size() > 0 && visited.size() < toSearch){
visitUrl(toVisit.get(0));
}
System.out.println("\n\n*done*\n\n");
}
public static void visitUrl(String url) {
List<String> ee = evaluateUrls(url);
searchTerm(url);
visited.add(url);
toVisit.remove(url);
toVisit.addAll(ee.stream().filter( e -> !visited.contains(e)).collect(Collectors.toList()));
toVisit.remove(0);
}
public static void searchTerm(String currentUrl) {
//if(userAgent.doc.getTextContent().contains(searchingTerm))
System.out.println(visited.size() +") "+ currentUrl);
}
public List<String> evaluateUrls(String currentUrl) {
List<String> subUrls = new ArrayList<>();
try {
Elements temp = userAgent.visit(currentUrl).findEvery("<a href>");
for (Element e : temp) {
String x = e.getAt("href");
subUrls.add(x);
}
}catch (Exception e) {
System.out.println(e);
}
return subUrls;
}
}

How to define array of objects in a properties file and read from Java program

I have a properties file like this.
property[0].name=A
property[0].value=1
property[1].name=B
property[1].value=2
property[2].name=C
property[2].value=3
How to read this file as a list of objects of a class {name, value} in plain java program using ResourceBundle or Properties?
Here is the class.
public class XYZ {
private String name;
private String value;
// Getters & Setters
}
I need to get like this.
ArrayList<XYZ> propertiesList = SomeUtility.getProperties("property", XYZ.class);
Utility class might be like this.
public class SomeUtility {
public static ArrayList getProperties(String key, Class cls) {
//logic
}
}
I might not understand exactly what you want so feel free to correct me and give me more constraints to work with but here is a simple way to read a Properties file located somewhere in your project:
private static void readPropertiesFile(String path) throws IOException {
java.util.Map<String, String> map = new java.util.LinkedHashMap<>();
Properties properties = new Properties();
InputStream inputStream = new FileInputStream(path);
properties.load(inputStream);
for (String name : properties.stringPropertyNames()) {
map.put(name, properties.getProperty(name));
}
for (java.util.Map.Entry<String, String> entry : map.entrySet()) {
System.out.printf("Property Key: %s, Property Value: %s%n", entry.getKey(), entry.getValue());
}
}
Output
Property Key: property[0].name, Property Value: A
Property Key: property[1].name, Property Value: B
Property Key: property[0].value, Property Value: 1
Property Key: property[1].value, Property Value: 2
Property Key: property[2].name, Property Value: C
Property Key: property[2].value, Property Value: 3
This is the solution I wrote, but it involves Reflect and Gson. Is there any better way to do this? Anything already available which is fine tuned like Apache's.
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import java.lang.reflect.Field;
import java.util.*;
public class ListResourceBundle {
public static final Gson gson = new Gson();
private final ResourceBundle bundle;
public ListResourceBundle(ResourceBundle bundle) {
this.bundle = bundle;
}
public List<?> getProperties(String key, Class<?> cls) {
final int maxArraySize = getMaxArraySize(key, getMatchingKeys(key));
final List<String> fields = getFields(cls);
final List<Object> result = new ArrayList<>();
for (int i = 0; i < maxArraySize; i++) {
JsonObject jsonObject = new JsonObject();
for (String field : fields) {
jsonObject.addProperty(field, getStringOrNull(key + "[" + i + "]." + field));
}
result.add(gson.fromJson(jsonObject, cls));
}
System.out.println("result.toString() = " + result.toString());
return result;
}
public List<String> getMatchingKeys(String key) {
Enumeration<String> keys = bundle.getKeys();
List<String> matchingKeys = new ArrayList<>();
while(keys.hasMoreElements()) {
String k = keys.nextElement();
if(k.startsWith(key)) {
matchingKeys.add(k);
}
}
Collections.sort(matchingKeys);
return matchingKeys;
}
public int getMaxArraySize(String key, List<String> matchingKeys) {
int maxArraySize = 0;
for (int i = 0; ; i++) {
boolean indexAvailable = false;
for (String matchingKey : matchingKeys) {
if(matchingKey.startsWith(key + "[" + i + "]")) {
indexAvailable = true;
break;
}
}
if(indexAvailable) {
maxArraySize++;
} else {
break;
}
}
return maxArraySize;
}
public String getStringOrNull(String key) {
try {
return bundle.getString(key);
} catch (MissingResourceException e) {
return null;
}
}
public List<String> getFields(Class<?> cls) {
final List<String> fields = new ArrayList<>();
for (Field field : cls.getDeclaredFields()) {
fields.add(field.getName());
}
return fields;
}
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("com.example.application.resources.Resource");
ListResourceBundle applicationResourceBundle = new ListResourceBundle(bundle);
applicationResourceBundle.getProperties("property", ReportParam.class);
}
}
Resource:
property[0].name=A
property[0].value=1
property[1].name=B
property[1].value=2
property[2].name=C
property[2].value=3
Output:
result.toString() = [
ReportParam{name='A', value='1'},
ReportParam{name='B', value='2'},
ReportParam{name='C', value='3'}]
Process finished with exit code 0
I know it's bit late of an answer, but if I understand your problem statement correctly, you can use :
#ConfigurationProperties
to get your job done.
Here is my spring-boot example with a YAML file for the sake of convenience (same can be achieved through properties file as well).
application.yaml:
xyz:
xyzprops :
-
name: cbc
value: 441
-
name: obc
value: 443
XYZ class:
#Component
#ConfigurationProperties(prefix = "xyz")
public class XYZ{
private List<XYZProps> xyzprops;
public List<XYZProps> getXyzprops() {
return xyzprops;
}
public void setXyzprops(List<XYZProps> xyzprops) {
this.xyzprops = xyzprops;
}
public class XYZProps{
String name;
String value;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
}
And then #Autowire XYZ where you want to use it.
I would use JSON:
in your file:
property=[{"name":"A","value":"1"},{"name":"B","value":"2"},{"name":"C","value":"3"}]
and then deserialize it using com.google.gson.gson (or any other) library:
ArrayList<XYZ> propertiesList;
propertiesList = new gsonbuilder().create().fromjson(property, propertiesList.class);
NOTE: I haven't tested this code, and i'm not very familiar with java so i am sure there is a better,cleaner way to implement this.

Using array as key for hashmap java

i have a method that puts some value(obtained from an excel file) into a hashmap with an array as the key
public HashMap<List<String>, List<String[]>> sbsBusServiceDataGnr() throws
IOException
{
System.out.println(engine.txtY + "Processing HashMap "
+ "sbsBusServiceData..." + engine.txtN);
int counterPass = 0, counterFail = 0, stopCounter = 0;
String dataExtract, x = "";
String[] stopInfo = new String[3];
List<String[]> stopsData = new ArrayList<String[]>();
List<String> serviceNum = new Vector<String>();
HashMap<List<String>, List<String[]>> sbsBusServiceData =
new HashMap<List<String>, List<String[]>>();
String dataPath = this.dynamicPathFinder(
"Data\\SBS_Bus_Routes.csv");
BufferedReader sbsBusServiceDataPop = new BufferedReader(
new FileReader(dataPath));
sbsBusServiceDataPop.readLine();
//Skips first line
while ((dataExtract = sbsBusServiceDataPop.readLine()) != null) {
try {
String[] dataParts = dataExtract.split(",", 5);
if (!dataParts[4].equals("-")){
if (Double.parseDouble(dataParts[4]) == 0.0){
sbsBusServiceData.put(serviceNum, stopsData);
String serviceNum1 = "null", serviceNum2 = "null";
if(!serviceNum.isEmpty()){
serviceNum1 = serviceNum.get(0);
serviceNum2 = serviceNum.get(1);
}
System.out.println("Service Number " + serviceNum1
+ ":" + serviceNum2 + " with " + stopCounter
+ " stops added.");
stopCounter = 0;
//Finalizing previous service
serviceNum.Clear();
serviceNum.add(0, dataParts[0]);
serviceNum.add(1, dataParts[1]);
//Adding new service
}
}
stopInfo[0] = dataParts[2];
stopInfo[1] = dataParts[3];
stopInfo[2] = dataParts[4];
stopsData.add(stopInfo);
//Adding stop to service
stopCounter++;
counterPass++;
}
catch (Exception e) {
System.out.println(engine.txtR + "Unable to process "
+ dataExtract + " into HashMap sbsBusServiceData."
+ engine.txtN + e);
counterFail++;
}
}
sbsBusServiceDataPop.close();
System.out.println(engine.txtG + counterPass + " number of lines"
+ " processed into HashMap sbsBusServiceData.\n" + engine.txtR
+ counterFail + " number of lines failed to process into "
+ "HashMap sbsBusServiceData.");
return sbsBusServiceData;
}
//Generates sbsBusServiceDataGnr HashMap : 15376 Data Rows
//HashMap Contents: {ServiceNumber, Direction},
// <{RouteSequence, bsCode, Distance}>
this method work for putting the values into the hashmap but i cannot seem to get any value from the hashmap when i try to call it there is always a nullpointerexception
List<String> sbsTest = new Vector<String>();
sbsTest.add(0, "10");
sbsTest.add(1, "1");
System.out.println(sbsBusServiceData.get(sbsTest));
try{
List<String[]> sbsServiceResults = sbsBusServiceData.get(sbsTest);
System.out.println(sbsServiceResults.size());
String x = sbsServiceResults.get(1)[0];
System.out.println(x);
} catch(Exception e){
System.out.println(txtR + "No data returned" + txtN + e);
}
this is a sample of the file im reading the data from:
SBS
How can i get the hashmap to return me the value i want?
Arrays are not suitable as keys in HashMaps, since arrays don't override Object's equals and hashCode methods (which means two different array instances containing the exact same elements will be considered as different keys by HashMap).
The alternatives are to use a List<String> instead of String[] as the key of the HashMap, or to use a TreeMap<String[]> with a custom Comparator<String[]> passed to the constructor.
If you are having fixed array size then the example I'm posting might be useful.
Here I've created two Object one is Food and Next is Product.
Here Food object is use and added method to get string array.
public class Product {
private String productName;
private String productCode;
public Product(String productName, String productCode) {
this.productName = productName;
this.productCode = productCode;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
}
Food Model Class: Use as a Object instead of String[] and achieve String[] functionality.
public class Food implements Comparable<Food> {
private String type;
private String consumeApproach;
public Food(String type, String consumeApproach) {
this.type = type;
this.consumeApproach = consumeApproach;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getConsumeApproach() {
return consumeApproach;
}
public void setConsumeApproach(String consumeApproach) {
this.consumeApproach = consumeApproach;
}
public String[] FoodArray() {
return new String[] { this.type, this.consumeApproach };
}
//Implement compareTo method as you want.
#Override
public int compareTo(Food o) {
return o.getType().compareTo(this.type);
}
}
Using HashMap example
public class HashMapKeyAsArray {
public static void main(String[] args) {
HashMap<Food,List<Product>> map = dataSetLake();
map.entrySet().stream().forEach(m -> {
String[] food = m.getKey().FoodArray();
Arrays.asList(food).stream().forEach(f->{
System.out.print(f + " ");
});
System.out.println();
List<Product> list = m.getValue();
list.stream().forEach(e -> {
System.out.println("Name:" + e.getProductName() + " Produc Code:" + e.getProductCode());
});
System.out.println();
});
}
private static HashMap<Food,List<Product>> dataSetLake(){
HashMap<Food,List<Product>> data = new HashMap<>();
List<Product> fruitA = new ArrayList<>();
fruitA.add(new Product("Apple","123"));
fruitA.add(new Product("Banana","456"));
List<Product> vegetableA = new ArrayList<>();
vegetableA.add(new Product("Potato","999"));
vegetableA.add(new Product("Tomato","987"));
List<Product> fruitB = new ArrayList<>();
fruitB.add(new Product("Apple","123"));
fruitB.add(new Product("Banana","456"));
List<Product> vegetableB = new ArrayList<>();
vegetableB.add(new Product("Potato","999"));
vegetableB.add(new Product("Tomato","987"));
Food foodA = new Food("Fruits","Read To Eat");
Food foodB = new Food("Vegetables","Need To Cook");
Food foodC = new Food("VegetablesC","Need To Cook C");
data.put(foodA, fruitB);
data.put(foodB, vegetableB);
data.put(foodA, fruitA);
data.put(foodC, vegetableA);
return data;
}
Using TreeMap example
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;
public class TreeMapKeyAsArray {
public static void main(String[] args) {
TreeMap<Food, List<Product>> map = dataSetLake();
map.entrySet().stream().forEach(m -> {
String[] food = m.getKey().FoodArray();
Arrays.asList(food).stream().forEach(f->{
System.out.print(f + " ");
});
System.out.println();
List<Product> list = m.getValue();
list.stream().forEach(e -> {
System.out.println("Name:" + e.getProductName() + " Produc Code:" + e.getProductCode());
});
System.out.println();
});
}
private static TreeMap<Food, List<Product>> dataSetLake() {
TreeMap<Food, List<Product>> data = new TreeMap<>();
List<Product> fruitA = new ArrayList<>();
fruitA.add(new Product("Apple", "123"));
fruitA.add(new Product("Banana", "456"));
List<Product> vegetableA = new ArrayList<>();
vegetableA.add(new Product("Potato", "999"));
vegetableA.add(new Product("Tomato", "987"));
List<Product> fruitB = new ArrayList<>();
fruitB.add(new Product("Apple", "123"));
fruitB.add(new Product("Banana", "456"));
List<Product> vegetableB = new ArrayList<>();
vegetableB.add(new Product("Potato", "999"));
vegetableB.add(new Product("Tomato", "987"));
Food foodA = new Food("Fruits", "Read To Eat");
Food foodB = new Food("Vegetables", "Need To Cook");
data.put(foodA, fruitB);
data.put(foodB, vegetableB);
data.put(foodA, fruitA);
data.put(foodB, vegetableA);
return data;
}
}

How to get hashmap key and value in java from another function

I have a json parse like this
public class SecondFragment extends Fragment implements OnClickListener {
// URL to get contacts JSON
private static String contestUrl = "http://api.apps.com/contest";
// JSON Node names
private static final String TAG_ITEM_ID = "id";
private static final String TAG_URL = "url";
private static final String TAG_START_DATE = "start_date";
private static final String TAG_END_DATE = "end_date";
// contacts JSONArray
JSONArray foods = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> foodslist;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
foodslist = new ArrayList<HashMap<String, String>>();
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(contestUrl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
String id = c.getString(TAG_ITEM_ID);
String name = c.getString(TAG_URL);
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_ID, id);
contact.put(TAG_URL, name);
contact.put(TAG_START_DATE, email);
contact.put(TAG_END_DATE, address);
String start_date = (String)contact.get(TAG_ITEM_ID);
// adding contact to contact list
foodslist.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
}
}
I have two function, onCreate and GetContacts. In the end of onCreate it call GetContacts and call this json.
My question is, how can I got the Hashmap value on GetContacts so I can use it on onCreate
So far, I got this to get the value of Hashmap
String start_date = (String)contact.get(TAG_ITEM_ID);
But, its only works on GetContacts.
Anyone can help me?
Thanks Before
There are couple of ways:
Way-1:
Create instance variable (class-level) of HashMap contact and then you can use it anywhere within class inclusing onCreate and getContacts method.
package stackoverflow.q_25034927;
import java.util.HashMap;
import java.util.Map;
public class PassVariable {
private static Map<String, String> contact = new HashMap<String, String>();
public void onCreate() {
//populate contact object as per your logic
getContacts();
}
private void getContacts() {
//Use contact object directly which was pre-populby onCreate method.
}
}
Way-2:
Pass map to the getContacts() method:
package stackoverflow.q_25034927;
import java.util.HashMap;
import java.util.Map;
public class PassVariable {
public void onCreate() {
final Map<String, String> contact = new HashMap<String, String>();
//populate contact object as per your logic.
getContacts(contact);
}
private void getContacts(Map<String, String> contact) {
//Use contact object which is passed as argument.
}
}
On other side, please use cameCasing while naming Java methods or variables. GetContacts is not right, make it getContacts.
For email and address fields, using TAG_START_DATE and TAG_END_DATE is no fun. :-)
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
To answer about #3 below, variable s is not accessible in NotInner class:
package com.test;
public class Test {
static String s = "";
}
class NotInner {
public static void main(String[] args) {
System.out.println(s); //Compilation error: s cannot be resolved to a variable
}
}
You have
List<Map<String,String>> foodslist = ...;
which is filled in the loop.
To get at individual values, iterate:
for( Map<String,String> item: foodslist ){
String id = item.get(TAG_ITEM_ID);
String name = item.get(TAG_URL);
String email = item.get(TAG_START_DATE);
String address = item.get(TAG_END_DATE);
}
Or you write a method for the class where you keep foodslist:
String getAttr( int i, String tag ){
return foodslist.get(i).get(tag);
}
and you can call
String id = xxx.getAttr( i, TAG_ITEM_ID );
So return the data ...
public List<Map<String, String>> getContacts() {
if (foodslist != null && foodslist.isEmpty()) {
return foodslist;
}
foodslist = new ArrayList<Map<String, String>>();
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
String id = c.getString(TAG_ITEM_ID);
String name = c.getString(TAG_URL);
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_ID, id);
contact.put(TAG_URL, name);
contact.put(TAG_START_DATE, email);
contact.put(TAG_END_DATE, address);
// adding contact to contact list
foodslist.add(contact);
}
return foodslist;
}
Though I'm not sure why that variable is called foodslist if it's supposed to contain contacts.

Spring mvc, making a menu data object

I'm really a newbie to JAVA, spring mvc.
And my understanding for "code" is so poor that I can't even think of how I'm going to get through with upcoming errors.
So this question will sound like " Do this for me!". ( It will do, actually )
Anyway, I'm trying to make a two-depth menu. Its structure looks like this below.
TopMenu
::: menuNo
::: menuName
::: memberType
::: url
::: sort
::: subMenus
::: menuNo
::: menuName
::: memberType
::: url
::: sort
TopMenu2
::: menuNo2
::: menuName2
::: memberType2
::: url2
.
.
.
.
So I made a bean class for this.
public class MenuInfoBean {
private String menuNo;
private String menuName;
private String memberType;
private String url;
private int sort;
List<MenuInfoBean> subMenus;
public MenuInfoBean() {
}
public String getMenuNo() {
return menuNo;
}
public void setMenuNo(String menuNo) {
this.menuNo = menuNo;
}
public String getMenuName() {
return menuName;
}
public void setMenuName(String menuName) {
this.menuName = menuName;
}
public String getMemberType() {
return memberType;
}
public void setMemberType(String memberType) {
this.memberType = memberType;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getSort() {
return sort;
}
public void setSort(int sort) {
this.sort = sort;
}
public List<MenuInfoBean> getSubMenus() {
return subMenus;
}
public void setSubMenus(MenuInfoBean subMenus) {
subMenus.menuName = subMenus.menuName;
subMenus.memberType = subMenus.memberType;
subMenus.url = subMenus.url;
subMenus.sort = subMenus.sort;
}
}
Which database will be used is not decided yet, so I'm temporarily using properties for menu data.
#TopMenu List
topmenu = M1000,M9000
#SubMenu List
M1000.submenu =
M9000.submenu = M9001,M9002,M9003,M9004
#TopMenu Info
#M1000 APPLICATION
M1000.menuName=APPLICATION
M1000.url=
M1000.memberType=00,10
M1000.sort=1
#M9000 ADMIN
M9000.menuName=ADMIN
M9000.url=/SYS01/memberList.mon
M9000.memberType=00,10
M9000.sort=1
#SubMenu Info
#M9000 ADMIN's
M9001.menuName=Member mgmt
M9001.url=/SYS01/memberList.mon
M9001.memberType=00,10
M9001.sort=1
M9002.menuName=menu2
M9002.url=/SYS01/memberList.mon
M9002.memberType=00,10
M9002.sort=1
M9003.menuName=menu3
M9003.url=/SYS01/memberList.mon
M9003.memberType=00,10
M9003.sort=1
M9004.menuName=menu4
M9004.url=/SYS01/memberList.mon
M9004.memberType=00,10
M9004.sort=1
And here I fetch the data and try to put them into a List.
public class MenuManager {
public List<MenuInfoBean> getMenus(String permissionCode) {
LabelProperties msgResource = LabelProperties.getInstance();
MenuInfoBean menuInfo = new MenuInfoBean();
List<MenuInfoBean> menuList = new ArrayList<MenuInfoBean>();
String topMenu = msgResource.getProperty("topmenu");
String[] topMenuItems = topMenu.split(",");
for (int i = 0; topMenuItems.length > i; i++ ) {
String subMenuName = msgResource.getProperty(topMenuItems[i] + ".submenu");
if ( subMenuName.isEmpty() == false ) {
menuInfo.setMenuName(msgResource.getProperty(subMenuName + ".menuName"));
menuInfo.setMemberType(msgResource.getProperty(subMenuName + ".memberType"));
menuInfo.setUrl(msgResource.getProperty(subMenuName + ".url"));
menuInfo.setSort(Integer.parseInt(msgResource.getProperty(subMenuName + ".sort")));
menuInfo.setSubMenus(menuInfo);
} else {
menuInfo.setMenuName("");
menuInfo.setSubMenus(menuInfo);
}
menuInfo.setMenuNo("");
menuInfo.setMenuName(msgResource.getProperty(topMenuItems[i] + ".menuName"));
menuInfo.setMemberType(msgResource.getProperty(topMenuItems[i] + ".memberType"));
menuInfo.setUrl(msgResource.getProperty(topMenuItems[i] + ".url"));
menuInfo.setSort(Integer.parseInt(msgResource.getProperty(topMenuItems[i] + ".sort")));
menuList.add(menuInfo);
}
return menuList;
}
}
getProperty method works great. It gets the properties value correctly.
But as you may noticed, there's some null data is being made.
to ignore this NullPointerException, I made
List<MenuInfoBean> menuList = new ArrayList<MenuInfoBean>();
So the exception has been successfully avoided. But another error comes up which isn't important in this post....
Anyway, while trying to solve the new error, I looked into the menuInfo data and found out something wrong was going on.
The subMenus was holding the topMenu's data!
Here's the question, How can I make this menu with MenuInfoBean like the structure I mentioned on the top of this post?
And why subMenus data was holding topMenu's properties?
I set subMenus data first, and topMenu data later! why this happens?
First of all I am updating the domain object by adding a additional method add(Meun)
import java.util.ArrayList;
import java.util.List;
public class MenuInfoBean
{
private String menuNo;
private String menuName;
private String memberType;
private String url;
private int sort;
List<MenuInfoBean> subMenus;
public MenuInfoBean()
{
}
public String getMenuNo()
{
return menuNo;
}
public void setMenuNo(String menuNo)
{
this.menuNo = menuNo;
}
public String getMenuName()
{
return menuName;
}
public void setMenuName(String menuName)
{
this.menuName = menuName;
}
public String getMemberType()
{
return memberType;
}
public void setMemberType(String memberType)
{
this.memberType = memberType;
}
public String getUrl()
{
return url;
}
public void setUrl(String url)
{
this.url = url;
}
public int getSort()
{
return sort;
}
public void setSort(int sort)
{
this.sort = sort;
}
public List<MenuInfoBean> getSubMenus()
{
return subMenus;
}
// This is new method added to the bean
public void addSubMenuItem(MenuInfoBean menuInfoBean)
{
if (subMenus == null)
subMenus = new ArrayList<MenuInfoBean>();
subMenus.add(menuInfoBean);
}
}
Here is the class that generate the menu and return (look at the get menu method):
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.lang.StringUtils;
public class MenuExtractionComponent
{
public List<MenuInfoBean> getMenus(String permissionCode)
{
LabelProperties msgResource = LabelProperties.getInstance();
List<MenuInfoBean> menuList = new ArrayList<MenuInfoBean>();
String topMenu = msgResource.getProperty("topmenu");
List<String> topMenuItems = new ArrayList<String>();
// Checking is top menu empty
if (StringUtils.isNotBlank(topMenu))
{
topMenuItems.addAll(Arrays.asList(topMenu.split(",")));
}
for (String topMenuItem : topMenuItems)
{
// Setting top menu details
MenuInfoBean menuInfo = new MenuInfoBean();
menuInfo.setMenuNo("");
menuInfo.setMenuName(msgResource.getProperty(topMenuItem + ".menuName"));
menuInfo.setMemberType(msgResource.getProperty(topMenuItem + ".memberType"));
menuInfo.setUrl(msgResource.getProperty(topMenuItem + ".url"));
menuInfo.setSort(Integer.parseInt(msgResource.getProperty(topMenuItem + ".sort")));
String subMenu = msgResource.getProperty(topMenuItem + ".submenu");
List<String> subMenuItems = new ArrayList<String>();
// Checking is sub menu empty
if (StringUtils.isNotBlank(subMenu))
{
subMenuItems.addAll(Arrays.asList(subMenu.split(",")));
}
for (String subMenuItem : subMenuItems)
{
MenuInfoBean subMenuInfo = new MenuInfoBean();
subMenuInfo.setMenuName(msgResource.getProperty(subMenuItem + ".menuName"));
subMenuInfo.setMemberType(msgResource.getProperty(subMenuItem + ".memberType"));
subMenuInfo.setUrl(msgResource.getProperty(subMenuItem + ".url"));
subMenuInfo.setSort(Integer.parseInt(msgResource.getProperty(subMenuItem + ".sort")));
menuInfo.addSubMenuItem(subMenuInfo);
}
menuList.add(menuInfo);
}
return menuList;
}
}

Categories