List of List String in java - java

I have a problem with the implementation of List>, it gives me always the last element duplicated. Here is a bunch of my code :
Here is the declaration of my list and the list of lists.
public List<List<String>> survs = new ArrayList<>();
public List<String> surveillance = new ArrayList<>();
public int k=0;
Here i add to the list some strings.
public void handleAddSURVClick(ActionEvent actionEvent) {
survName = name.getText();
max = maxp.getText();
min = minp.getText();
surveillance.add(survName);
surveillance.add(monitoredObject);
surveillance.add(monitoredProperty);
surveillance.add(max);
surveillance.add(min);
// Add surveillance to the vector
survs.add(k, surveillance);k++;
//Surv initialisation
survName = ""; name.clear();
max = ""; maxp.clear();
min = ""; minp.clear();
monitoredObject = "";
monitoredProperty = "";
}
then simply i add the list to the list of lists and i specify an index in which i wanna store my list and i print the list of lists ( survs )
survs.add(k, surveillance);k++;
System.out.println(survs);
Unfortunately, it gives me this result after submitting two lists, it gives just the last one redundant:
[[yas, ProductSurrounding, charge, 667, 524, stack, ProductSurrounding, charge, 8787, 6422], [yas, ProductSurrounding, charge, 667, 524, stack, ProductSurrounding, charge, 8787, 6422]]
if i do surveillance.clear(), the results will be two empty lists [[],[]]
Thank you in advance

Create new instance of surveillance after each time you add it to the survs.But crate survs this instance only once.
Do like this :
public void handleAddSURVClick(ActionEvent actionEvent) {
survName = name.getText();
max = maxp.getText();
min = minp.getText();
surveillance=new ArrayList<>();
surveillance.add(survName);
surveillance.add(monitoredObject);
surveillance.add(monitoredProperty);
surveillance.add(max);
surveillance.add(min);
// Add surveillance to the vector
survs.add(k, surveillance);k++;
//Surv initialisation
survName = ""; name.clear();
max = ""; maxp.clear();
min = ""; minp.clear();
monitoredObject = "";
monitoredProperty = "";
}
And if you do surveillance.clear() then you are clearing the value in the reference of surveillance in your survs.So at the end all becomes empty.

Related

I'm trying to iterate through two arrays in Java, while also checking to see if the values are equal

I am trying to iterate through many arrays, two at a time. They contain upwards of ten-thousand entries each, including the source. In which I am trying to assign each word to either a noun, verb, adjective, or adverb.
I can't seem to figure a way to compare two arrays without writing an if else statement thousands of times.
I searched on Google and SO for similar issues. I couldn't find anything to move me forward.
package wcs;
import dictionaryReader.dicReader;
import sourceReader.sourceReader;
public class Assigner {
private static String source[], snArray[], svArray[], sadvArray[], sadjArray[];
private static String nArray[], vArray[], advArray[], adjArray[];
private static boolean finished = false;
public static void sourceAssign() {
sourceReader srcRead = new sourceReader();
//dicReader dic = new dicReader();
String[] nArray = dicReader.getnArray(), vArray = dicReader.getvArray(), advArray = dicReader.getAdvArray(),
adjArray = dicReader.getAdjArray();
String source[] = srcRead.getSource();
// Noun Store
for (int i = 0; i < source.length; i++) {
if (source[i] == dicReader.getnArray()[i]) {
source[i] = dicReader.getnArray()[i];
}else{
}
}
// Verb Store
// Adverb Store
// Adjective Store
}
}
Basically this is a simpler way to get a list of items that are in both Lists
// construct a list of item for first list
List<String> firstList = new ArrayList<>(Arrays.asList(new String[0])); // add items
//this function will only keep items in `firstList` if the value is in both lists
firstList.retainAll(Arrays.asList(new String[0]));
// iterate to do your work
for(String val:firstList) {
}

Java: find Id By Title () from models

This is my function, to find a id from list by matching titles
public static int findIdByTitle(List<Integer> IDs, List<String> Titles ,String title){
for (int i = 0; i < IDs.size(); i++){
if (Titles.get(i).equals(title))
return IDs.get(i);
}
return 0;
}
This function search in model list and find id
But I can't use this because:
int id = findIdByTitle(Core.userSignIn.getBasicList().getGradeList().get(****?****).getID()
,Core.userSignIn.getBasicList().getGradeList().get(****?****).getName()
,spinnerGrade.getSelectedItem().toString());
I must give it a number position : ( see the lists.get(****?****).getID() or getName()
I want using that's function for all models not just for this model
give 2 lists and a matching word, use matching word to find position of that's in list, and give me a ID of this position
All of my model have ID , Title and some of them have ParentID
with help of Nitin , My problem has been resolved:
List<String> Titles = new ArrayList<>();
List<Integer> IDs = new ArrayList<>();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Titles = Core.userSignIn.getBasicList().getGradeList().stream().map(GradeList::getGradeName).collect(Collectors.toList());
IDs = Core.userSignIn.getBasicList().getGradeList().stream().map(GradeList::getGradeID).collect(Collectors.toList());
} else {
Titles = new ArrayList<>(Core.userSignIn.getBasicList().getGradeList().size());
IDs = new ArrayList<>(Core.userSignIn.getBasicList().getGradeList().size());
for (GradeList gradeList : Core.userSignIn.getBasicList().getGradeList()) {
Titles.add(gradeList.getGradeName());
IDs.add(gradeList.getGradeID());
}
}
educationList1.setiGradeID(findIdByTitle(IDs
,Titles
,spGrade.getSelectedItem().toString()));
You first have to convert your list to List of Integer and List of String and then pass it to your method. You can use below code if you are using Java 8:
final List<Integer> testList1 = BasicList().getGradeList().stream().map(Test::getId).collect(Collectors.toList());
final List<String> testList2 = BasicList().getGradeList().stream().map(Test::getName).collect(Collectors.toList());
Replace your class name in place of Test in above code.
Use below code for below java 8 env:
List<String> strings = new ArrayList<>(BasicList().getGradeList().size());
for (Test test : BasicList().getGradeList()) {
strings.add(test.getName());
}
Similar for Ids.
You need another loop if you want to get all Ids of your models, you can do something like this :
List<Integer> listId=new ArrayList<Integer>();
for(int i=0; i<BasicList().getGradeList().size(); i++) {
listId.add(findIdByTitle(BasicList().getGradeList().get(i).getID()
,BasicList().getGradeList().get(i).getName()
,spinnerGrade.getSelectedItem().toString()));
}

Add equal values in a ArrayList in Android

I am storing scores in a ArrayList, but when the user has a score equal to a previous score, the second one is not added to the ArrayList. How can I add equal values to a ArrayList (or use another type of List)?
Code:
[...]
ArrayList<String> savedArray = new ArrayList<>();
Set<String> gandula = new HashSet<>();
[...]
public Preferencias(Context contextoParametro) {
contexto = contextoParametro;
preferences = contexto.getSharedPreferences(NOME_ARQUIVO, MODE);
editor = preferences.edit();
}
public void addMediaGeral(double mediaGeral) {
//Save Score
Set<String> set = new HashSet<String>();
if (!getMediaGeral().get(0).equals("0")) {
savedArray.addAll(getMediaGeral());
}
savedArray.add(String.valueOf(mediaGeral));
set.addAll(savedArray);
editor.putStringSet(KEY_MEDIA_GERAL, set);
editor.commit();
}
public ArrayList<String> getMediaGeral(){
//get score
Set<String> set = preferences.getStringSet(KEY_MEDIA_GERAL, gandula);
ArrayList<String> list = new ArrayList<String>(set);
return list;
}
[...]
Retrieving in my activity:
[...]
mediaGeral = score;
preferencias.addMediaGeral(Double.parseDouble(mediaGeral));
[...]
ArrayList<String> string_medias = new ArrayList<>();
string_medias = preferencias.getMediaGeral();
ArrayList<Float> float_medias = new ArrayList<>();
for (int j = 0; j < string_medias.size(); j++){
float_medias.add(Float.parseFloat(string_medias.get(j)));
}
Log.i("TESTANDO PRF", "TAMANHO DA LISTA: "+float_medias.size());
Float[] dataObjects = float_medias.toArray(new
Float[float_medias.size()]);
doChart(float_medias);
[...]
I scored 0.33333 three times (I'll config decimal places) but it is showing only one score 0.3333.
Printscreen: http://prntscr.com/f1vx3h
But the chart accepts duplicates. Printscreen: http://prntscr.com/f1vxng (i manipulated the scores in the last printscreen).
A Set does not allow for duplicate values.
Doing this:
set.addAll(savedArray);
discards all your duplicates.
These answers may be of help.
Saving a JSON object as a string in preferences would probably be the way to go.
ArrayList accept duplicate this should not be your problem but I saw that your store yours score in a HashSet uses a hashMap instead because:
In the case of HashMap, it replaces the old value with the new one.
In the case of HashSet, the item isn't inserted.

How to link elements of two linked list in java?

This is my starting code for a van rental database.
List<String> manual = new LinkedList<>();
List<String> automatic = new LinkedList<>();
List<String> location = new LinkedList<>();
manual.add("Queen");
manual.add("Purple");
manual.add("Hendrix");
automatic.add("Wicked");
automatic.add("Zeppelin");
automatic.add("Floyd");
automatic.add("Ramones");
automatic.add("Nirvana");
location.add("CBD");
location.add("Penrith");
location.add("Ceremorne");
location.add("Sutherland");
How can I link the cars to the location.
For example, location CBD has Wicked,Zepplin and Floyd, and Penrith has Queen.
So if the command line arguement has "Print CBD" then it must show the vans available in CBD.
Any help will be appreciated.
This is hardly a database. They are just three separate data pieces. Use some object-oriented design technique to create classes, such as a class called Van. For example, it's not java code exactly, just for example.
Class Van {
string name;
VanType type; // e.x, Enum {auto, manual}
Location location; // another class
}
I think you would be better off using the approach explained In This Post. I believe this would be a much clearer implementation.
I hope this helps.
Ok thats the code.
We are using only linked list as you wanted.
(linked list keeps track on the input order so we are using that too)
As it is one to many relation we should have some kind of "foreign key" so we can see the related object. For each car you add no matter manual or auto, you should add a key for the location as you can see below
for example rels[0] = 3; means that your first car will have relation with 4th object of the locations list. thats implemented in the code - take a look.
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class TestMain {
public static void main(String[] args) {
List<String> manual = new LinkedList<String>();
List<String> automatic = new LinkedList<String>();
List<String> location = new LinkedList<String>();
int[] rels = new int[8];
//cars with relations
rels[0] = 1;
manual.add("Queen");
rels[1] = 1;
manual.add("Purple");
rels[2] = 1;
manual.add("Hendrix");
rels[3] = 1;
automatic.add("Wicked");
rels[4] = 0;
automatic.add("Zeppelin");
rels[5] = 0;
automatic.add("Floyd");
rels[6] = 1;
automatic.add("Ramones");
rels[7] = 2;
automatic.add("Nirvana");
//key-0
location.add("CBD");
//key-1
location.add("Penrith");
//key-2
location.add("Ceremorne");
//key-3
location.add("Sutherland");
//here is the value that you have from your input args[] for example
String desiredLocation = "CBD";
int index = getLocationIndex(location, desiredLocation);
//if desired location not found we will print nothing
if(index==-1)return;
List mergedCars = new LinkedList<String>();
mergedCars.addAll(manual);
mergedCars.addAll(automatic);
for (int i = 0; i < rels.length; i++) {
if(index == rels[i])
{
System.out.println(mergedCars.get(i));
}
}
}
private static int getLocationIndex(List<String> location, String desiredLocation) {
int counter=0;
for (Iterator iterator = location.iterator(); iterator.hasNext();) {
String temp = (String) iterator.next();
if(temp.equals(desiredLocation))
{
return counter;
}
counter++;
}
return -1;
}
}

How to get random string value without duplicate?

I want to fetch only a single company name and I want to fetch it only once. So if it already was fetched, it should not be fetched again.
Here is the code:
private static String[] billercompanies = {
"1st",
"TELUS Communications",
"Rogers Cablesystems",
"Shaw Cable",
"TELUS Mobility Inc",
"Nanaimo Regional District of",
"Credit Union MasterCard",
};
public static String GetBillerCompany(){
String randomBillerComp = "";
randomBillerComp = (billercompanies[new Random().nextInt(billercompanies.length)]);
return randomBillerComp;
}
Just shuffle the array you want using Collections
Collections.shuffle(List);
So simply create a list from your array
List<E> list = Arrays.asList(array);
Then shuffle it using the method above
Collections.shuffle(list);
Your list can be read from left to right as it was random.
So simply save the index
int currentIndex = 0;
public E getRandom(){
//If at the end, start over
if(++currentIndex == list.size()) {
currentIndex = 0;
shuffle(list);
}
return list.get(currentIndex);
}
Each time you want to forget the duplicate list you already used, simply shuffle the array again
Collections.shuffle(list);
Without index
You could simply remove the first value each time, once the list is empty, recreate it with the original array. As Ole V.V. pointer out, a List generated by Arrays.asList(E[]) doesn't support the remove methods so it is necessary to generate a new instance from it.
Here is a quick and simple class using this solution :
public class RandomList<E>{
E[] array;
List<E> list;
public RandomList(E[] array){
this.array = array;
buildList(array);
}
public E getRandom(){
if(list.isEmpty()) buildList(array);
return list.remove(0);
}
public void buildList(E[] array){
list = new ArrayList<E>(Arrays.asList(array));
Collections.shuffle(list);
}
}
And the test was done with this small code :
Integer[] array = {1,2,3,4,5};
RandomList<Integer> rl = new RandomList(array);
int i = 0;
while(i++ < 10)
System.out.println(rl.getRandom());
Make a copy in a List and remove the element when it was already fetched.
Arrays.asList(array) is not modifiable but you can wrap it in a full featured List.
List<String> billercompaniesList = new ArrayList<>(Arrays.asList(billercompanies));
String randomBillerComp = "";
Random random = new Random();
// first retrieval
int index = random.nextInt(billercompaniesList.size());
randomBillerComp = billercompaniesList.get(index);
billercompaniesList.remove(index);
// second retrieval
index = random.nextInt(billercompaniesList.size());
randomBillerComp = billercompaniesList.get(index);
billercompaniesList.remove(index);
// and so for

Categories

Resources