List of tuples in Android? - java

I do not find possibility of "list of tuples" in Java. What alternative structure do you suggest where can be stored in a list / array?
In other languages like in Swift, declaring it looks like this:
var items: [(id: String, text: String, totalMatch: Int16)] = [];
I would avoid declaring a class, fields.

SQL
I don't know what you really want to do. But if you want to manage Data you could use a sql liste Database provided per dafault by android.
Your Objects would be stored very lightweight but you have to give a lot of effort.
Class/ArrayList
Otherwise just use a ArrayList. Until you dont have more than 10000 Items its no Problem even on older Devices.
You will need two classes.
class Item{
String id;
String text;
int totalMatch;
}
class YourClass{
ArrayList<Item> items = new ArrayList<Item>();
}
JSON Parser
Very good and easy parser for JSON Files is GSON from Google: See:
https://github.com/google/gson

Old question but if anyone still in need of, possibly you can try Pair class from android.util package inside List. Something like this:
List<Pair<String, Integer>> myPairList = new ArrayList<>();

Related

How to efficiently locally store instances of an object in Java

I am kind of a beginner in Java. I have this college project where we are asked to build a train booking system (desktop). As part of the app, the admin can add and edit new routes. I want to store those instances of different routes somewhere, but how? I want to be able to add as many as I want, but lists and arrays require for a size to be determined. How can I store indefinite instances of an object efficiently? This is the data I want to store for each instance:
int routeId;
String deptPoint;
String destPoint;
String transpMode;
int vehicleId;
Note: we must use Java data types, no DBs allowed.
Some help would be appreciated! Thanks :)
but lists and arrays require for a size to be determined.
Incorrect. Arrays have a set size, but not lists. A List implementation (if mutable) supports automatic dynamic resizing, up to a limit of two billion items or running out of memory.
Define your class. Here we use the records feature in Java
16+ for brevity. But if you need mutable objects, declare a conventional class instead.
record Route( int routeId, String deptPoint, String destPoint, String transpMode, int vehicleId ) {}
Declare a list to hold objects of that class.
List< Route > routes = new ArrayList<> () ;
Instantiate Route objects, and collect.
routes.add( new Route( … ) ) ;
In fact, Java lists are not requiring predetermined size, they will change as you add elements and remove them, so they're perfectly fine to store Java objects. Thing you didn't mention is do you need to persist it or not, if you don't need to then you can just do that. If you need to, you'll need database or store it to the file on your machine.
You could build an object that have this fields and put it in a List:
public class Route {
int routeId;
String deptPoint;
String destPoint;
String transpMode;
int vehicleId;
}
As deHaar suggested, one option would be to store your values in a text file with JSON format. You could use gson to convert to/from JSON really easy. You then only have to implement the mechanism to store this JSON in a local file following this example.

How to store list of realm object to Arraylist in android [duplicate]

I have RealmResults that I receive from Realm like
RealmResults<StepEntry> stepEntryResults = realm.where(StepEntry.class).findAll();
Now I want convert RealmResults<StepEntry> to ArrayList<StepEntry>
I have try
ArrayList<StepEntry> stepEntryArray = new ArrayList<StepEntry>(stepEntryResults));
but the item in my ArrayList is not my StepEntry object, it is StepEntryRealmProxy
How can I convert it?
Any help or suggestion would be great appreciated.
To eagerly read every element from the Realm (and therefore make all elements in the list become unmanaged, you can do):
List<StepEntry> arrayListOfUnmanagedObjects = realm.copyFromRealm(realmResults);
But you generally have absolutely no reason to do that unless you want to serialize the objects with GSON (specifically, because it reads field data with reflection rather than with getters), because Realm was designed in such a way that the list exposes a change listener, allowing you to keep your UI up to date just by observing changes made to the database.
The answer by #EpicPandaForce works well. I tried this way to optimize my app performance and I find the following is a bit faster. Another option for people who prefer speed:
RealmResults<Tag> childList = realm.where(Tag.class).equalTo("parentID", id).findAll();
Tag[] childs = new Tag[childList.size()];
childList.toArray(childs);
return Arrays.asList(childs);
In Kotlin:
var list : List<Student>: listof()
val rl = realm.where(Student::class.java).findAll()
// subList return all data contain on RealmResults
list = rl.subList(0,rl.size)

JSON Values extends another JSON values

My Json structure is like
main = {
"hideIds1":["id1","id2","id3","id4"],
"hideIds2":["id11","id12","id13","id14"],
"maindHides1":["hideIds1","id7","id9"]
"maindHides2":["hideIds1","hideIds2","id14","id18"]
}
Looks "mainHides1" is extends all the values of "hideIds1".When i iterate "mainHides1" i have to check the key is having the values or not in the main JsonObject.In this iteration, first value becomes true but for other ids it wont need.
What i am expect here is when i access the "maindHides1" values it becomes like ["id1","id2","id3","id4","id7","id9"]. Will json do it automatically something like extends or i have to do it manually in program?
Or anyother samrtway to handle this problem.
You can use GSON library and caste your JSON into java object.Once you have java object with you you can do your required task.
For the option of manual, you can create your own hashset with keys from JSON and what you can do is that while adding values you can cross check if they are equal to any current key values. if yes then you can add its values in internal loop to the value set.
In JSON itself it is not possible but I suggest using something like TypeScript and just create your models as you want, It will be something like that:
interface IMainModel {
IDs: array;
}
var donut: IHides1Model = {
main: IMainModel,
IDs: array
};
JSON is pure type construction it is not a class,library or framework.
You would need to make this extension manually.

2D Array that can hold multiple values with no limits

I am quite new to java currently working on a not-so-simple web browser application in which I would like to record a permanent history file with a 2D array setup with 3 columns containing "Date Viewed", "URL", "How many times this URL has been viewed before".
Currently I have a temporary solution that only saves "URL" which is also used for "Back, Foward" features using an ArrayList.
private List tempHistory = new ArrayList();
I am reading through the Java documentation but I cannot put together a solution, unless I am missing the obvious there is no 2D array as flexible a ArrayList like in Python?
From your description it doesn't sound like you need a 2D array. You just have one dimension -- but of complex data types, right?
So define a HistoryItem class or something with a Date property for date viewed, URL for URL, int for view count.
Then you just want a List<HistoryItem> history = new ArrayList<HistoryItem>().
The reason I don't think you really want a 2D array-like thing is that it could only hold one data type, and you clearly have several data types at work here, like a date and a count. But if you really want a table-like abstraction, try Guava's Table.
No, there is no built-in 2D array type in Java (unless you use primitive arrays).
You could just use a list of lists (List<List>) - however, I think it is almost always better to use a custom type that you put into the list. In your case, you'd create a class HistoryEntry (with fields for "Date viewed", URL etc.), and use List<HistoryEntry>. That way, you get all the benefits a proper type gives you (typechecking, completion in an IDE, ability to put methods into the class etc.).
How do you plan to browse the history then? If you want to search the history for each url later on then ArrayList approach might not be efficient.
I would rather prefer a Map with URL as key.
Map<Url,UrlHistory> browseHistory = new HahMap<Url,UrlHistory> ();
UrlHistory will contains all the fields you want to associate with a url like no. of times page was accessed and all.

converting a complex json object to java object through gson

I've a problem with storing a Json object as a java object, I'm not sure what structure to use to store something like this:
'tags':[{'CouchDB':1},{'JSON':1},{'database':1},{'NoSQL':1},{'document_database':1}]
I have tried 2 dimensional arrays, ArrayLists and Hashtables but didn't work, could be down to my poor implementation or I just have it wrong, need help with this ASAP please!
I'm using GSON to convert from the Json String to the Java object, and have other parts working fine, the problem is just having GSON parse this structure properly
Try using http://jsonlint.com/ to make sure that your JSON is valid (it doesn't seem to be)
If you change your tags to {"name":"couchdb"}, your Java class could look like this:
public class Tag
{
private String name;
...
}
And your container class could have a private List<Tag> tags;
Seems, like your tags are just a bunch of keys with a count (or something along those lines) attached to each one, i.e. key-value pairs which is just a hashtable e.g.:
{'tags':{'CouchDB':1,'JSON':1,'database':1,'NoSQL':1,'document_database':1}}
You should be able to convert the above without any trouble, if you can't I would say you have some sort of configuration issue as opposed to any kind of problem with the format of the data.

Categories

Resources