updating particular item in list - java

I have an list of customer object. I need to read them from shared preferences and check for particular object by id with my new object and replace the old one in list with new object and write it to back to pref. This is what I am doing..Is it right?
List<School> schools = readFromPref();
ListIterator<School> iterator = schools.listIterator();
while (iterator.hasNext()) {
School oldSchool = iterator.next();
if (oldSchool.getId().equalsIgnoreCase(newSchool.getId())) {
iterator.set(newSchool);
schools.add(newSchool);
}
}
writeToPref(schools);

Remove schools.add(newSchool); because iterator.set(newSchool); is updating your school list already.
And everything looks good

You can use Enhanced For loop to get and update data in your ArrayList.
ArrayList<School> schools = readFromPref();
int i=0;
for(School oldSchool : schools){ //Enhanced For loop
if(oldSchool.getId().equalsIgnoreCase(newSchool.getId())){
oldSchool.setId(newSchool.getId());
schools.set(i, oldSchool);
}
i++;
}
writeToPref(schools);
Here is the link of how to save and retrive Object from SharedPreference using Gson.

Store your data in form of map where key will be the id of your object,and update the object on key basis

Related

How can I obtain the list of values for a given key and add the list of values to a newly created list?

So I'm going crazy with this one. This is for an assignment and can't seem to get this to work at all!!
I have the following HashMap:
HashMap<String, ArrayList<Team>> teams;
(Team being another class to obtain the details of the teams)
What I need to be able to do is get the List of teams for the Key(String) from the above HashMap, and assign the List to a local variable I have declared:
List<Team> results = teams.get(division);
But this is where I get stuck. I have no idea how I'm suppose to complete this task.
As a further note "division" is the Key used in the HashMap. The ArrayList is a list of teams that belong to the division.
I have tried the below, which does not compile at all. Really not sure how I can get this to work!!
public void recordResult(String division, String teamA, String teamB, int teamAScore, int teamBScore)
{
List<Team> results = teams.get(division);
for (String i : teams.keySet())
{
results = new ArrayList<Team>();
results.add();
}
}
**You can ignore the arguments after the "String division". These will be used later.
Iterate over the entrySet() of the Map. Now you can fetch each List for that specific key and proceed further. Something like:
for (Entry<String, ArrayList<Team>> entry : teams.entrySet()) {
// extract the value from the key using `teams.get(entry.getKey())`
// proceed further with the value obtained
}

Java - adding new Object within an if() statement to a list declared outside if(){}

I have this code where the ArrayList was instantiated outside any condition:
List<PatientDto> list = new ArrayList<PatientDto>();
for(Object o : ObjectList){
if(true){
PatientDto patient = new PatientDto(....);
list.add(patient);
}
}
PatientDto dto = list.get(0);
Will I still be able to retrieve the new PatientDto() as I access the list, given that it was instantiated within the if statements?
yes
Patient is inside the scope of your if clause but it can be accessed outside the block if you have access to the reference for the same outside the if clause.
The list has stored a reference of your patient object which will be accessible whereever you can access the list. Hence, you can access your contained object by fetching it from the list.
Yes, since you are inserting it in to the list, you can get it by using index. Or you can iterate after insertion of all the objects later.
for ex:
PatientDto patient = list.get(index);
update :
PatientDto dto = list.get(0);
Yes, that gives the 0th indexed PatientDto from the list, which whatever you put earlier in that place. Since you adding new instances in the loop, they give you the same.
coming to the scope
for(Object o : ObjectList){
if(true){
PatientDto patient = new PatientDto(....);
list.add(patient);
}
}
System.out.println(patient); // err, I dont know what is patient
System.out.println(list.get(0)) // yay here is the patient, use it.

How to Iterate Two Lists and compare the items within?

I'm almost at the end of my final project in the university, I'm trying to control my inStock with my current Stock of articles.
My stock contains the following attributes:
int idMercaderia;
int cantidad;
int idSucursal;
I have two lists that contains Inventario type POJOs:
List <Inventario> stock = new InventarioDAO().findAll();
List <Inventario> inStock = new ArrayList <Inventario>();
Before persist in the database, I want to compare the attribute idMercaderia in both of 'em, if they're the same don't create another entry and just add the quantity cantidad to the current stock and do a saveOrUpdate() if not just create another entry.
I'm really stuck in this part and currently run out of ideas after trying iterate both Lists but I can't figure out the stock thingy.
Any help/code will be really appreciated.
you need to implement an equals() method if not already happened in the Inventario to compare idMercaderia in there. then
for(Inventario item: stock){
if(inStock.contains(item)){
item.cantidad++;
}
}
Create a Map<Integer, Inventario> of your first list to map an idMercaderia to one Inventario. Then iterate your second list and check for each item the corresponding one in the map.
Map<Integer, Inventario> map = new HashMap<Integer, Inventario>();
for (Inventario item : stock) {
map.put(item.getIdMercaderia(), item);
}
and
for (Inventario item : inStock) {
int idMercaderia = map.getIdMercaderia();
Inventario inventario = map.get(idMercaderia);
if (inventario == null) {
// error handling
continue;
}
if (item.getCantidad() == inventario.getCantidad() {
// handle
}
}

How to find duplicates in an ArrayList which is in the form of JSON object?

I am having an option in my website for the user i.e: "Settings" in that I given 3 options(TextBoxes) to enter details: 1.E-mail, 2.SMS, 3.MMS.. in this user can enter another mail id: its an optional thing but, if he enter the both or same which is neccesary e-mail and optional or same then, I have to tell that "given e-mail" alredy exist.
I am sending this data as ArrayList that to coverted as JSON object.
What is the best way to find the duplicate and notify that to user
Help me in this
Thanks in advance
Either parse it into Java collections with a JSON framework of your choice, then check for duplicates or use JavaScript to directly work on the JSON.
If you have the ArrayList anyway, why don't iterate over that?
Please do the following
HashSet hashSet = new HashSet(arrayList1);
ArrayList arrayList2 = new ArrayList(hashSet) ;
if(arrayList2.size()<arrayList1.size()){
//duplicates exits
}
You can do what Ammu posted, but this will not identify the duplicate entry. If you have the ArrayList as a Java object (if not, convert it into one), convert the ArrayList into a HashSet, compare the size to identify if there are duplicate entries. If so, you need to sort the ArrayList in order to find the duplicate entry.
Collections.sort(arrayList);
for(int i = 1; i < arrayList.size() - 1; i++){
if (arrayList.get(i).equals(arrayList.get(i - 1))){
// found duplicate
System.out.println("Duplicate!");
}
}
this works only if the entries of the ArrayList implement the sortable interface. But since your ArrayList is filled with strings this is the case.
Based on what you described
"... in this user can enter another
mail id: its an optional thing but, if
he enter the both or same which is
neccesary e-mail and optional or same
then, I have to tell that "given
e-mail" alredy exist."
I would alert the user using Javascript and avoid the HTTP Request/Response round-trip to the server:
...
// before submitting the form
if (document.getElementById('requiredEmail').value == document.getElementById('optionalEmail').value) {
alert("The optional email must be different than the required email");
}
...
As suggested before by other user, you can just create a Set based on the ArrayList if you are validating the input in the backend...
String[] parsedInput = new String[] { "SMS-Value", "MMS-Value", "email#domain.com", "email#domain.com" }
List<String> receivedList = Arrays.asList(parsedInput);
Set<String> validatedList = new HashSet<String>(receivedList);
if (validatedList.size() < receivedList.size()) {
throw new IllegalArgumentException("The email addresses provided are incorrect.");
}
If you want to find the duplicates then you can iterate over the list and find.
like:
Map<Object, Integer> map = new HashMap<Object, Integer>();
for(Object obj : list)
{
if(map.containsKey(obj))
{
map.put(obj, map.get(obj)+1);
}
else
{
map.put(obj, 1);
}
}
Objects in the map having value more than 1 are duplicate.
If you just want to get rid of duplicates (rather than knowing which are actually duplicates)
Ex:
Set set = new HashSet(list);
set can not have duplicate elements, so it will remove all duplicates.

How we get the List objects in backward direction?

Hi i am getting List object that contains pojo class objects of the table. in my case i have to show the table data in reverse order. mean that, for ex
i am adding some rows to particular table in database when i am added recently, the data is storing at last row in table(in database). here i have to show whole content of the table in my jsp page in reverse order, mean that what i inserted recently have to display first row in my jsp page.
here my code was like,
List lst = tabledate.getAllData();//return List<Table> Object
Iterator it = lst.iterator();
MyTable mt = new MyTable();//pojo class
while(it.hasNext())
{
mt=(MyTable)it.next();
//getting data from getters.
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
}
Use a ListIterator to iterate through the list using hasPrevious() and previous():
ListIterator it = lst.listIterator(lst.size());
while(it.hasPrevious()) {
System.out.println(it.previous());
}
You cannot use an iterator in this case. You will need to use index based access:
int size = lst.size();
for (int i=size - 1; i >= 0; i --)
{
MyTable mt = (MyTable)lst.get(i);
....
}
Btw: there is no need to create a new MyTable() before the loop. This is an instance that will be thrown away immediately and serves no purpose.

Categories