Android substring values in arraylist - java

I'm pulling data from database into an arraylist. I want to manipulate the arraylist and get a substring of the results. How can I substring the values generated in carList below?
private ArrayList<Cars> carList;
carList = CarDAO.getCarsByEngine(engineType);

Assuming you have a attribute String name in car.
String searchStr = "your_str";
for(i=0; i<carList.size();i++){
carList[i].name;
if(searchStr.toLowerCase().contains(carList[i].name.toLowerCase())){
// do somethig with your object carList[i]
}
}

Related

Find all non-matching items, based on an input parameter, in an array and return it as a new array

I have an array of company names and I want to see if they match a certain value.
In fact, I want a list of all non-matching values. Something like this:
"One or more companies: [company1], [company2] are not equal to [checkCompany]
Example:
checkCompany = "GM"
companies = ["GM", "GM", "Ford"]
In this case there would only be one company not equal to "GM" but there could be more than one.
This function should simply work, its arguments are the companies array and the checkCompanies string that you want to check against.
The function then returns tempList which includes all the values that do not match with checkCompanies string.
import java.util.ArrayList;
public ArrayList<String> checkList(ArrayList<String> companies, String checkCompany) {
ArrayList<String> tempList = new ArrayList<String>();
for(int i = 0; i < companies.size(); i++) {
if(!companies.get(i).equals(checkCompany)) {
tempList.add(companies.get(i));
}
}
return tempList;
All you would then have to do is format the return to give you the string you want to output!
checkCompany = "GM"
companies = ["GM", "GM", "Ford"]
nonMatchedCompanies = list()
for(String company : companies){
if(!company.contains(checkCompany)
nonMatchedCompanies.add(company)
}
nonMatchedCompanies is the result which will contain all not matched companies from the list. This will check if the checkCompany is part of company name.

Access Values from an ArrayList That is inside another ArrayList

java.util.List records = new java.util.ArrayList();
java.sql.ResultSet rs = selectestatement.executeQuery(query1);
while (rs.next()) {
java.util.List record = new java.util.ArrayList();
record.add(rs.getString("WHLO").trim());
record.add("888509018579");
record.add(rs.getString("ITEM_CODE").trim());
record.add(rs.getString("ARRIVAL_DATE").trim());
record.add(rs.getString("PAIRS_PER_CASE").trim());
record.add(rs.getString("ATS").trim());
records.add(record);
}
In this code, Final arraylist is the "records array". This records arraylist contents few record arrays.
How can i access the 1st element of record arraylist from the records arraylist?
Don't use raw types:
List<List<String>> records = new ArrayList<>();
List<String> record = new ArrayList<>();
...
records.add(record);
This way records.get(i) will return a List<String> instead of an Object, so you can access the elements of the inner List:
String first = records.get(0).get(0);
What you really want is a class containing your row data.
class RecordData {
public String whlo;
public long someNumber = 888509018579;
public String itemCode;
public String arrivalDate;
public String pairsPerCase;
public String ats;
}
and then do
java.util.List<RecordData> records = new java.util.ArrayList<>();
while (rs.next()) {
RecordData record = new RecordData();
record.whlo = rs.getString("WHLO").trim();
record.itemCode = rs.getString("ITEM_CODE").trim();
record.arrivalDate = rs.getString("ARRIVAL_DATE").trim();
record.pairsPerCase = rs.getString("PAIRS_PER_CASE").trim();
record.ats = rs.getString("ATS").trim();
records.add(record);
}
In fact, you want to make the members private and accessible via getters and setters, and use LocalDate for the arrivalDate and int for the pairsPerCase member, but the first point is not using a List to store the retrieved values but wrap it in a business-oriented class.
You can do something like this
((ArrayList)records.get(0)).get(0) to access the first element of the array list that is in the first position of the records array list.
Please note that if you specify what does the records contains (in this case records will contains array lists) then you won't need to cast the element to array list.
List<List<String>> records = new ArrayList<ArrayList>();
{...}
records.get(0).get(0); //You don't need the cast because Java already knows that what it is inside records are Lists

Split Arraylist of 2 types when printing it

I have a list composed of Objects
Every object is comprised of 2 different values
int number;
String name;
ArrayList<Object> objectList= new ArrayList<Object>();
I have another list composed of Cars
Every Car has one value
String type;
ArrayList<Cars> carList= new ArrayList<Cars>();
I want to print half the objectList first then the carList then the other half of the objectList
Like so.. for example:
Output= "number + type + name"
Basically i want the second list to be printed in between the first list.I searched the web but i am not really sure what i should be looking for and how exactly to code this.
Again i am sorry for the bad question.. i am trying to learn coding by myself because i can't afford it.
Thanks in advance.
Just iterate through the first list, and use the index to access the corresponding Object in the second list:
for(int i = 0; i < objectList.size(); i++){
Object obj = objectList.get(i);
Car car = carList.get(i);
//Print Here
}
You say you want to print half of your list first, then you are able to split the original list by half:
Streams.of(objectList.sublist(0, length/2),
carList,
objectList.sublist(length/2, length))
.flatMap(Collection::stream)
.forEach(o -> {
if (o instanceof YourObject) {
YourObject o1 = (YourObject)o;
// Print with YourObject
} else if (o instanceof Cars) {
// Print car objects
}
})
You can very easily achieve this by a for loop.
But as per your output format
The size of the objectList and carList must be same for this to work.
Try something like this :
for(int i=0;i<objectList.size();i++){
String name; int number;
number = objectList.get(i).number;
name = objectList.get(i).name;
String type = carList.get(i).type;
System.out.Println(name+type+number);
}
As per your comment, if carList is in another class and is private then, you need to set a getter method that takes an index and returns the type
Like this :
public class A{
private ArrayList<Car> carList = new ArrayList();
........ //some codes
public String getTypeAtIndex(int i){ return carList.get(i).type; }
}
Then anywhere you can call
A a;
String type = a.getTypeAtIndex(i);

Error Parsing a string to a List

I have managed to fetch a string from the database and be able to store some of its elements in variable so as to reduce the number of times the app interacts with the databse. However I wanted the first element to be fetched from the database to be stored in a list but it keeps generating an error when i parse the string to a new list. please help
//String fetched from the database
final String[] rec = split(myresult,seperator);
//loc is the first String to be parsed to a String..
//desc is the 2nd string to be parsed to a textarea
//coords 3rd string which contains coordinates..
String loc=rec[0];
final String desc=rec[1];
String coords=rec[2];
//ERROR IS GENERATED HERE!!!
listmboya=new List(loc);
//Separate the coordinates in the string...
String seperator2=",";
String [] coordinates=split(coords,seperator2);
String lat=coordinates[0];
String lot=coordinates[1];
//convert them to floats..
item1=Float.parseFloat(lat);
item2=Float.parseFloat(lot);
list is an iterface,
try
listmboya=new ArrayList();
listmboya.add(loc);
You cannot instantiate List object. Its an interface and not a class. You need an ArrayList which is the implementing class of List and also, there is no constructor for ArrayList that takes String as parameter.
So, you need to create an ArrayList<String> and then add your String to it.
So you need to do it like this: -
List<String> listmboya=new ArrayList<String>();
listmboya.add(loc);
Make sure to declare your listmboya as List<String>
UPDATE: - Post some more Code in case this doesn't work. We need to look at more of them.
List is the abstract class, can not be instantiated.
just try like this:
listmboya = new ArrayList<String>();
listmboya.add(loc);

How to convert String representation of ArrayList to ArrayList

I have an ArrayList, Whom i convert to String like
ArrayList str = (ArrayList) retrieveList.get(1);
...
makeCookie("userCredentialsCookie", str.toString(), httpServletResponce);
....
private void makeCookie(String name, String value, HttpServletResponse response) {
Cookie cookie = new Cookie(name, value);
cookie.setPath("/");
response.addCookie(cookie);
} //end of makeCookie()
Now when i retrieve cookie value, i get String, but i again want to convert it into ArrayList like
private void addCookieValueToSession(HttpSession session, Cookie cookie, String attributeName) {
if (attributeName.equalsIgnoreCase("getusercredentials")) {
String value = cookie.getValue();
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
return;
}
String value = cookie.getValue();
session.setAttribute(attributeName, value);
} //end of addCookieValueToSession
How can i again convert it to ArrayList?
Thank you.
someList.toString() is not a proper way of serializing your data and will get you into trouble.
Since you need to store it as a String in a cookie, use JSON or XML. google-gson might be a good lib for you:
ArrayList str = (ArrayList) retrieveList.get(1);
String content = new Gson().toJson(str);
makeCookie("userCredentialsCookie", content, httpServletResponce);
//...
ArrayList userCredntialsList = new Gson().fromJson(cookie.getValue(), ArrayList.class);
As long as it's an ArrayList of String objects you should be able to write a small method which can parse the single String to re-create the list. The toString of an ArrayList will look something like this:
"[foo, bar, baz]"
So if that String is in the variable value, you could do something like this:
String debracketed = value.replace("[", "").replace("]", ""); // now be "foo, bar, baz"
String trimmed = debracketed.replaceAll("\\s+", ""); // now is "foo,bar,baz"
ArrayList<String> list = new ArrayList<String>(Arrays.asList(trimmed.split(","))); // now have an ArrayList containing "foo", "bar" and "baz"
Note, this is untested code.
Also, if it is not the case that your original ArrayList is a list of Strings, and is instead say, an ArrayList<MyDomainObject>, this approach will not work. For that your should instead find how to serialise/deserialise your objects correctly - toString is generally not a valid approach for this. It would be worth updating the question if that is the case.
You can't directly cast a String to ArrayList instead you need to create an ArrayList object to hold String values.
You need to change part of your code below:
ArrayList userCredntialsList = (ArrayList)value; //Need String to ArrayList
session.setAttribute(attributeName, userCredntialsList);
to:
ArrayList<String> userCredentialsList = ( ArrayList<Strnig> ) session.getAttribute( attributeName );
if ( userCredentialsList == null ) {
userCredentialsList = new ArrayList<String>( 10 );
session.setAttribute(attributeName, userCredentialsList);
}
userCredentialsList.add( value );

Categories

Resources