I want to create a multidimensional array where each of the nodes will have the following details:
Place Name ex: "Mysore" , "Bangalore"
Icon name ex: "waterfall", "wildlife"
Place Distance ex: "200", "123"
Which is the best way to do this when I have over 30 values ?
Example:
"Bangalore", "200", "city"
"Mysore", "100", "historic"
I am trying to populate a list array in Android where each row has three details - name, icon, distance so I want to temp populate that data in my java class.
Don't use a multidimensional array. Use a simple array (or List) of objects:
public class Place {
private String name;
private String icon;
private int distance;
// constructor, methods skipped for brevity
}
...
private Place[] places = new Place[10];
// or
private List<Place> places = new ArrayList<Place>();
Java is an OO language. Learn to define and use objects.
I think best option is create custom defined object.
Class TestObject
{
String Place,Icon,Distance;
// Setter and Getter method
}
// Create object of class. Store your value using setter and getter method
and save object into list
List<TestObject> test = new ArrayList<TestObject>();
test.add(testObject); //
Create a class with the attributes that you want in an element.
now you can create an array of objects of this class.
class Place {
private String name;
private String icon;
private int distance;
public Place(String name,String icon,int distance){
this.name=name;
this.icon=icon;
this.distance=distance;
}
}
Place places[]=new Place[10];
places[0]=new Place("Mysore","wildlife",123);
and so on
beware of instantiating the objects else you will endup getting NullPointerException
If you don't want to create a separate class . You can also use JSON for your purpose.
JSON object is light weight and can manage aaray data very easily.
Like :
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
ja.put("Mysore");
ja.put("wildlife");
ja.put(123);
jo.add(KEY, ja); // Adding array to JSON Object with key [KEY can be any unique value]
JSON are easy to read and manageable.
It provides lots of functionality rather than array.
Related
i have list of masters that have two fields that are name and rating and after serialization to array node i need to add one more field to each object
for example i have json
[{"masterName":"Bruce","rating":30},{"masterName":"Tom","rating":25}]
and i have list of servisec in json format that look like that
[{"masterName":"Bruce","services":["hair coloring","massage"]},{"masterName":"Tom","services":["hair coloring","haircut"]}]
i need it to looks something like that
[{"masterName":"Bruce","rating":30,"services":"hair coloring,massage"},{"masterName":"Tom","rating":25,"services":"hair coloring, haircut"}]
How can do it by using jackson?
I would approach it this way. Since you want to use Jackson.
First of all, I would extend the Master class by adding the services (which seems to be an array with Strings).
So the class would look something like this:
public class Master
{
private String masterName;
private int rating;
private List<String> services = new ArrayList<>(); // THE NEW PART
// Whatever you have else in your class
}
Then you could get your JSON array, I am supposing that it comes as a String for simplicity. Serialize this array in an array with Master objects and then you can add the services as said above.
e.g.
String yourJsonString = "[{\"masterName\":\"Bruce\",\"rating\":30},{\"masterName\":\"Tom\",\"rating\":25}]";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<Master> theListOfMasters = new ArrayList<>();
// Read them and put them in an Array
Master[] mastersPlainArr = mapper.readValue(yourJsonString, Master[].class);
theListOfMasters = new ArrayList(Arrays.asList(mastersPlainArr));
// then you can get your masters and edit them..
theListOfMasters.get(0).getServices.add("A NEW SERVICE...");
// And so on...
// Then you can turn them in a JSON array again:
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(theListOfMasters);
I have some list of objects:
List<Object> objectList = new ArrayList<>();
Object.class looks like this:
public class Object {
private String name;
private String age;
... getters & setters ...
}
I want to assign / replace all 'name' parameters inside my objectList to one value, f.e.: "Andrew".
Normally I would do it through iteration, but is there a way to do it without iterating? I have tried collections.replaceAll but failed:
Collections.replaceAll(objectList, object, new Object.setName("Andrew"));
objectList = objectList.forEach(object -> object.setName("Andrew"));
Setting the name field to static you can achieve this only. otherwise you must have to iterate over it.
I am attemping to populate a JComboBox with the names of cities.
My program has a class called 'Country'. The Country object contains a HashMap of objects called 'City' with a method getName, returning a String value.
public class Country {
private final Map<String, City> cities = new HashMap<>();
public Collection<City> getCities() {
return cities.values();
}
}
public class City {
String cityName;
public String getName() {
return cityName;
}
}
Is it possible to return an String array of cityName without using a loop? I was trying the following but it did not work:
Country country 1 = new Country();
String[] cityNames = country1.getCities().toArray();
JComboBox cityChoice = new JComboBox(cityNames);
This returns an Array of City objects, however I am not sure how to use the City getName method in conjunction with this.
You can not avoid looping. Either, you will loop, or Java will loop in the background.
You can avoid writing your own loop if keys in your map are city names. Then, you could only ask .keySet() from the map. But, even in that case, Java would loop in the background and copy the keys.
Other way is that you loop, but hide the loop in some method (lets say getCitiesArray()) in the class. So, you could do country1.getCitiesArray(); in the calling method. Code would look better and be easier to read, but you would still need to have loop inside of the class.
You can store Map key as CityName then do below to get Names.
cities.keySet();
The city object can be used directly in the combobox with some minor alterations.
public class City {
String cityName;
public String getName() {
return cityName;
}
#Override
public String toString() {
return getName();
}
}
Then the population code
Country country1 = new Country();
City[] cities = country1.getCities().toArray();
JComboBox<City> cityChoice = new JComboBox<City>(cities);
You should probably override hashCode and equals also.
If you are using Java 8, you can use the Stream API to map the names of the cities to a String:
String []cityNames = country1.getCities().stream().map(City::getName).toArray(String[]::new);
I was wondering if there was anyway to treat col_1,col_2...etc as a list rather than separate elements, using the SIMPLE XML Library for Android. I have been reading a bit about substitutions but I'm still confused.
Current Format :
<box-headers
dataTable="boxscore"
col_1="FINAL"
col_2="1"
col_3="2"
col_4="3"
col_5="4"
col_6="5"
col_7="6"
col_8="7"
col_9="8"
col_10="9"
col_11="R"
col_12="H"
col_13="E">
table
</box-headers>
I want to be able to parse out the col's as a list of some sort so I can handle any number of cols. Is this possible?
As ng said before: Use a Converter for this. Simple is brilliant in letting you customize every step of processing (while on the other hand it's possible to let you (de-)serialize even complex structures with some lines of code).
So here's an example:
A Class that will hold the values from the list:
#Root(name = "example")
#Convert(value = ListConverter.class) // Specify the Converter that's used for this class
public class Example
{
// This element will be set with the values from 'box-headers' element
#ElementList(name = "box-headers")
private List<String> values;
// This constructor is used to set the values while de-serializing
// You can also use setters instead
Example(List<String> values)
{
this.values = values;
}
//...
}
The Converter:
public class ExampleConverter implements Converter<Example>
{
#Override
public Example read(InputNode node) throws Exception
{
List<String> list = new ArrayList<>(); // List to insert the 'col_' values
NodeMap<InputNode> attributes = node.getAttributes(); // All attributes of the node
Iterator<String> itr = attributes.iterator();
while( itr.hasNext() ) // Iterate over all attributes
{
final String name = itr.next(); // The name of the attribute
if( name.startsWith("col_") ) // Check if it is a 'col' attribute
{
// Insert the value of the 'col_' attribute
list.add(attributes.get(name).getValue());
}
}
// Return the result - instead of a constructor you can use setter(s) too
return new Example(list);
}
#Override
public void write(OutputNode node, Example value) throws Exception
{
// TODO: Implement serializing here - only required if you want to serialize too
}
}
How to use:
// Serializer, don't forget `AnnotationStrategy` - without it wont work
Serializer ser = new Persister(new AnnotationStrategy());
// Deserialize the object - here the XML is readen from a file, other sources are possible
Example ex = ser.read(Example.class, new File("test.xml"));
This example uses only col_xy attributes, everything else is dropped. If you need those values too it's easy to implement them. You only have to retrieve them from the InputNode and set them into your output.
I'm a beginner Java and Gson user and have been able to apply it to my needs. I now have some JSON data that I need to parse into a spinner as follows:
{
"lang":[
"arabic",
"bengali",
"dutch-utf8",
"eng_root",
"english",
"english-utf8",
...
],
"themes":{
"blue":{
"chinese_ibm500":1,
"spanish":1,
"bengali":1,
"japanese":1,
"english":1,
"russian":1,
"french-utf8":1,
"eng_root":1,
"arabic":1,
"spanish-utf8":1,
"portuguese":1,
...
},
"green":{
"eng_root":1,
"engmonsoon":1,
"english":1
...
},
"red":{
"chinese_ibm500":1,
"spanish":1,
"bengali":1,
...
}
}
}
So from this JSON I need 2 things:
1) the array under lang is dynamic as for its the languages installed on the server. How could I get all the entries?
I have a class as follows but im stuck as to what I should do after I return lang
public class ListData {
private List<Language> lang;
public List<Language> getLang {
return lang;
}
public static class Language {
???
}
}
2) after understanding 1 I might be able to figure this one out. Under themes are colors which again can be more or less {purple, orange, whatever}. I just need a list of those themes, as far as I'm concerned I don't need to know the languages for each.
Feel like this question is turning into a book. I have searched SO extensively and hate asking questions but I'm pretty stumped. Thanks in advance.
1) In order to get the "lang" array, just modify
private List<Language> lang;
for
private List<String> lang;
Since the elements inside "lang" array are all strings, you don't need any class Language to store those values, they'll be parsed correctly as strings. And it doesn't matter how many strings the array contains...
2) In order to parse "themes", you have to notice that it's not an array [ ], but an object { }, so you do need to parse it with some object, and the most suitable class here is a Map like this:
private Map<String, Object> themes;
Note: as you said that you don't need the data under "blue", "green", etc... you can just Object as the value type in the map, otherwise you'd need some class...
Using a Map here allows you to have an arbitrary number of themes in your JSON response.
So in summary, you just need a class like:
public class ListData {
private List<String> lang;
private Map<String, Object> themes;
//getters & setters
}
and parse your JSON with:
Gson gson = new Gson();
ListData data = gson.fromJson(yourJsonString, ListData.class);
Your list of langs will be under:
data.getLang();
and your list of themes will be under:
data.getThemes().keySet();
I suggest you to take a look at Gson documentation. It's quite short and clear and you'll understand everything much better...