Randomise an ArrayList<Object> in Java - java

Given that i have an arrayList of company objects. I want to shuffle the objects inside listcompanies. listcompanies has a list of object companies inside it. I want to shuffle the company objects inside the listcompanies arraylist.
This is my company object
public class Company {
private String id;
private String companyName;
private String currentTaskId;
private String task1_id;
private String task1_url;
private String task1_title;
private String task1_description;
private String task1_type;
private String task2_id;
private String task2_url;
private String task2_title;
private String task2_description;
private String task2_type;
private String task3_id;
private String task3_url;
private String task3_title;
private String task3_description;
private String task3_type;
private String task4_id;
private String task4_url;
private String task4_title;
private String task4_description;
private String task4_type;
private String task5_id;
private String task5_url;
private String task5_title;
private String task5_description;
private String task5_type;
}
This is how i store data:
//create a company ArrayList
ArrayList<Company> listcompanies = new ArrayList<>();
for(int i = 0 ; i < 60 ; i ++){
//Initialise a new company per iteration
Company company = new Company();
//store data
company.setcompanyName("Name: " + i);
company.setcompanycurrentTaskId(i+"");
listcompanies.add(company);
}
I tried doing this to shuffle listcompanies but it didn't work.
// I TRIED doing this for sorting the listcompanies
long seed = System.nanoTime();
Collections.shuffle(listcompanies, new Random(seed));
// nothing happened it did not sort the list of companies

My question was a little confusing. Though i already figured it out the shuffle method randomises the data when it's included in the arraylist. Thus it was random all along.

Related

List All Data Using Retrofit/OkHttp With Response List

I have some codes that fetch some data from my API. My question is how can I list all the objects that I fetched before without using this jsonData.get(0), I expect something like jsonData.get(i), so I assume using something like below, but I can't use it, so how can I do that? Thanks.
for (int i=0;i<jsonData.length();i++){
MainActivity.java
List<Promo> jsonData = response.body();
Log.i("TESTER",""+jsonData);
String promoID = jsonData.get(0).getId_promo();
String promoTipe = jsonData.get(0).getPromo_type();
String promoValue = jsonData.get(0).getValue_based();
String promoName = jsonData.get(0).getPromo_name();
With POJO class that looks like this
Promo.java
public class Promo {
#SerializedName("id_promo")
private String id_promo;
#SerializedName("promo_name")
private String promo_name;
#SerializedName("promo_type")
private String promo_type;
#SerializedName("value_based")
private String value_based;
#SerializedName("quota")
private String quota;
#SerializedName("id_event")
private String id_event;
#SerializedName("description")
private String description;
public String getId_promo() {
return id_promo;
}
public void setId_promo(String id_promo) {
this.id_promo = id_promo;
}
public String getPromo_name() {
return promo_name;
}
}
ApiUrl.java
#FormUrlEncoded
#POST("promopublic")
Call<List<Promo>> getPromo(
#Field("id_event") String id_event,
#Field("total_buyer") String totalBuyer,
#Field("id_user") String id_user,
#Field("id_ticket") String id_ticket);
Using for loop like below solved my problem
for (int i=0;i<jsonData.size();i++){}

Filter parent and child at Realm - Android

I have two classes that I mapped as RealmObject and I would like to do a query that will filter both the parent and the child.
The query will filter all the products that are greater than the passed date and inside it filter all the compras that have date greater than the passed date.
Is it possible with a query or I really need to execute the query for products and after take this List and remove the compras that I don't want ?
public class Produto extends RealmObject implements Id{
#PrimaryKey
private Long id;
#Index
#Required
private String codigoBarras;
private String nome;
private String marca;
private String categoria;
private String subCategoria;
private Double quantidade;
private String unidade;
private byte[] imagemData;
private Date dataAlteracao;
private RealmList<Compra> compras;
...
public class Compra extends RealmObject implements Id{
#PrimaryKey
private Long id;
//#LinkingObjects("compras")
private Produto produto = null;
private Double preco;
private String local;
private String mercado;
private Date data;
private Boolean liquidacao = false;
private String observacao;
private Date dataAlteracao;
...
public List<Produto> buscarProdutoEComprasPorDataAlteracao(Long dataAlteracao) {
RealmResults<Produto> results = realm.where(Produto.class)
.greaterThan("dataAlteracao", new Date(dataAlteracao))
.greaterThan("compras.dataAlteracao", new Date(dataAlteracao))
.sort("codigoBarras")
.findAll();
return realm.copyFromRealm(results);
}
//#LinkingObjects("compras")
private Produto produto = null;
You can replace this with
#LinkingObjects("compras")
private final RealmResults<Produto> isComprasOfProdutos = null;
Although if your current query doesn't work, unfortunately Realm-Java does not support SUBQUERY nor the ALL predicate, and https://github.com/realm/realm-java/issues/5730 was never added nor do I think they will ever add it, so you'll have to do this manually. :(

How to convert List<Entity> to a string?

Here is the code :
I have a entity named ClassA which consists of following attribute
#JsonProperty("rowDeleted")
private Boolean rowDeleted;
#JsonProperty("start")
private List<Start> start = null;
#JsonProperty("end")
private List<End> end = null;
#JsonProperty("rows")
private List<Row> rows = null;
And Row is another entity which consists of attributes:
#JsonProperty("cells")
private List<Cell> cells = null;
#JsonProperty("clusteringKey")
private String clusteringKey;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
And Cell is another entity:
#JsonProperty("deleted")
private Boolean deleted;
#JsonProperty("name")
private String name;
#JsonProperty("value")
private String value;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
I am getting an object of ClassA and want to convert it into another entity which is ClassB contains fields:
private String end;
private String key;
private String keyspacename;
private String partitiondeleted;
private String rowdeleted;
private String rows;
private String start;
private String tablename;
private String triggerdate;
private String triggertime;
So basically i want to convert List rows of ClassA to String rows of ClassB.
Can anyone please suggest a way to do this.
Thanks in advance
suppose you have a list of class A.
List<A> list= . . . ;
List<B> newList=list
.stream()
.map(obj-> new B()
.setKey(obj.getKey())
.setKeyspacename(//set which field of class A will be saved)
.setPartitiondeleted()
// set more fields
)
.collect(Collecters.toList());
and then serialize this newlist into String by using jakson.
I wanted a string which could represent json format so modified my toString() as per my requirement and it solved my purpose.

Converting Arraylists with abstract objects

Good morning all,
While writing my GUI I ran into a problem with my Arraylist.
In my Vereniging class there is a ArrayList containing Persoon objects, which are either Lid or Medewerker.
Now what I need is to filter all the Lid objects from that list and make a new Arraylist with Lid objects.
Does anyone know if this is possible?
I've tried running a enhanced for loop and adding the objects to a new Arraylist but it says the datatype doesnt meet (trying to add Persoon to a Lid list)
Classes;
Vereniging
public class Vereniging {
private String naam;
private ArrayList<Persoon> personen;
private ArrayList<Vliegtuig> vliegtuigen;
private ArrayList<Vlucht> vluchten;
private ArrayList<Hangaar> hangaars;
private DataHandler handler = new Database();
public Vereniging(String naam){
this.naam = naam;
personen = new ArrayList<>();
vliegtuigen = new ArrayList<>();
vluchten = new ArrayList<>();
hangaars = new ArrayList<>();
}
public ArrayList<Persoon> getPersonen() {
return personen;
}
Persoon
public abstract class Persoon implements Comparable<Persoon>{
private String voornaam;
private String tussenvoegsel;
private String achternaam;
private String woonplaats;
private String geslacht;
private String rekeningnr;
Persoon(String voornaam, String tussenvoegsel, String achternaam, String
woonplaats,
String geslacht, String rekeningnr){
this.voornaam = voornaam;
this.tussenvoegsel = tussenvoegsel;
this.achternaam = achternaam;
this.woonplaats = woonplaats;
this.geslacht = geslacht;
this.rekeningnr = rekeningnr;
}
Lid
public class Lid extends Persoon {
private String gebnaam;
private String wachtwoord;
private String rol;
public Lid(String voornaam, String tussenvoegsel, String achternaam, String woonplaats, String geslacht,
String rekeningnr, String gebnaam, String wachtwoord, String rol) {
super(voornaam, tussenvoegsel, achternaam, woonplaats, geslacht, rekeningnr);
this.gebnaam = gebnaam;
this.wachtwoord = wachtwoord;
this.rol = rol;
}
You can use the type comparison operator: instanceof. Which lets you compare if a variable is an instance of a class (or a subclass).
See the following example which iterates over the personen list and then uses the instanceof to determine if it in fact is an instance of Lid or not:
List<Lid> lids = new ArrayList<>();
for(Persoon persoon : personen){
if(persoon instanceof Lid){
// safe cast and add to lids
lids.add((Lid) persoon);
}
}
If you happen to use Java 8, you can make us of the new Stream API:
List<Lid> lids = personen.stream() // create a stream of persoonen
.filter(Lid.class::isInstance) // equivalent to using instanceof
.map(Lid.class::cast) // equivalent to casting
.collect(Collectors.toList()); // creating a list
As I can see you want to add object of parent into array list of child type.
So when your are iterating through list of persoon, check type of persoon by using instanceOf then type case that to Lid and add it to your new list.
Hope this will resolve your problem.
More Enhance solution can be as following.
personen.stream().filter(p->p instanceOf Lid).map(p->(Lid)p).collect(Collectors.toList());
by using stream API of Java 8 you can do it in a single line.
Thanks!

Object ArrayList loses String values after deserialization?

so i have a three class video store GUI and it is supposed to save records of videos in stock. however it saves the video objects using serialization but for some reason ,even though i am not getting any errors, only the numerical values are making it through..
notice how the leftmost three columns and the rightmost column are all empty. this is because they are meant to have strings in them, and yet they dont...
as i said im not getting any errors so this truly confuses me.
constructor of VideoStore.java(the GUI class):
public VideoStore() {
initComponents();
model = (DefaultTableModel)displayVideos.getModel();
try{
BinaryFile = new BinaryFile();
BinaryFile.load();
}
catch(Exception e){
}
for(int j = 1; j < BinaryFile.videosList.size(); j ++) {
Video load = (Video)BinaryFile.videosList.get(j);
String tempName = load.getVideoName();
String tempProd = load.getProducer();
String tempRat = load.getRating();
String tempGenre = load.getGenre();
short tempNum = load.getVidNum();
float tempPrice = load.getvideoPrice();
try {
Object[] row = {ID, tempName, tempProd, tempGenre, tempPrice, tempNum, tempRat};
model.addRow(row);
} catch(Exception e){
}
ID++;
}
}
and then the BinaryFile class that i use to handle the .ser file:
public void load(){
try
{
FileInputStream fileIn = new FileInputStream("/Users/hanaezz/Desktop/output.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
videosList = (ArrayList)in.readObject();
in.close();
fileIn.close();
} catch(Exception i)
{
i.printStackTrace();
return;
}
}
public static void adderoo(Video v) {
videosList.add(v);
}
finally, the video class that is in the ArrayList:
private static String videoName;
private static String producer;
private static String rating;
private static String genre;
private short videoNumber;
private float videoPrice;
Static variabled are NOT serialized, you should put:
private String videoName;
private String producer;
private String rating;
private String genre;
private short videoNumber;
private float videoPrice;
in your video class.
The only static variable you should put in a Serializable class is serialVersionUID (which is used by the serialization and deserialization process). As in:
private static final long serialVersionUID = 1L;

Categories