Check ArrayList contains any specific data - java

I have an Arraylist:
public static ArrayList<ScheduleItem>[] data = (ArrayList<ScheduleItem>[]) new ArrayList[30];
Also, I have an another ArrayList which contain 3 dates:
public static ArrayList<String> dateWay = new ArrayList<String>();
Now, I want to check if a certain day is in the data Arraylist. If not, only then it will parse json file. I tried with this but, It throws null pointer exception
if(!ScheduleItem.data[getPageNumber].get(pageNumber).getDate().equals(ScheduleItem.dateWay.get(pageNumber))){
//method to parse json
}

ArrayList<ScheduleItem> data = new ArrayList<ScheduleItem>();
Date date = new Date(); //set your date
for(ScheduleItem item: data){
if(date.equals(item.getDate()){
System.out.println("Contains the date");
}
}

Related

How to access and read the values of child objects of an object?

Here is how I am constructing an Object inside a method:
//right after creating the class
public static ArrayList<Object> old_devicelist = new ArrayList<Object>();
//inside a method
Date date = new Date();
long time = date.getTime();
Integer opened = 0;
String deviceId = "";
String dev_rssi = "";
Object[] MyObject = new Object[]{time, opened, deviceId, dev_rssi};
old_devicelist.add(MyObject);
Now, I would like to loop through that ArrayList and access some elements (note that deviceId might at some point contain an object and I would like to access id field of it) inside it, then I would like to use them like this, for ex. :
if(device.id == 33){
//do something...
}
You're using an array with type Object and then you're storing these object arrays into a list. This makes it hard to retrieve the information later.
Consider this instead:
public static List<Device> DEVICES = new ArrayList<>();
class Device {
Date date;
long time;
Integer opened;
String deviceId;
String deviceRssi
Device(Date date, Integer opened, String deviceId, String deviceRssi) {
this.date = date;
this.time = date.getTime();
this.opened = opened;
this.deviceId = deviceId;
this.deviceRssi = deviceRssi;
}
}
Device first = new Device(
new Date(),
0,
"",
"");
DEVICES.add(first);
System.out.println(DEVICES.get(0).deviceId);
...
for (Device device : DEVICES) {
if (device.deviceId.equals("33)) {
// ...
}
}
I'd recommend not using too many static/global variables and reading about the Java Naming Convention.
I guess you should create new class instead of using Object.
public class DeviceSpecification { //or any other name
long time;
Integer opened;
String deviceId;
String dev_rssi;
public DeviceSpecification(long time, Integer opened, String deviceId, String dev_rssi) {
this.time = time;
this.opened = opened;
this.deviceId = deviceId;
this.dev_rssi = dev_rssi;
}
}
Create a list with specific type:
public static List<DeviceSpecification> oldDeviceCollection = new ArrayList<>();
Create an instance of a class
DeviceSpecification device = new DeviceSpecification(new Date().getTime(), 0, "", "")
Add the instance to a list
oldDeviceCollection.add(device);
Use it in query - we can use streams from Java 8
oldDeviceCollection.stream()
.forEach(
device -> {
if(device.id.equals("33")) {
// do something
}
);
First of all your Arraylist takes Objects and you are trying to add an Object array so if your goal is to keep object arrays with the device_id you should change your Arraylist to
public static ArrayList<Object[]> old_devicelist = new ArrayList();
Taking that in mind you can access any deviceid by typing
old_devicelist.get(i)[2]
where i is the element you want and 2 because you have setted device_id to be the 3rd element of your Object array!
Hope this helps!

Sort List<String[]> by order of Dates in Java

I have a List of String arrays of the form
List<String[]> currentLoadAddressLocations = new ArrayList<>();
That gets set and parsed through a JSONObject Array
try {
JSONObject dataObject = new JSONObject(data);
JSONArray dataObjArray = dataObject.getJSONArray("stops");
Log.i(TAG, dataObjArray.toString());
for (int i = 0; i < dataObjArray.length(); i++) {
JSONObject addressAndLocation = dataObjArray.getJSONObject(i);
addressGPointJSON.add(addressAndLocation.getString("address"));
locationGPointJSON.add(addressAndLocation.getString("location"));
cityGPointJSON.add(addressAndLocation.getString("city"));
stateGPointJSON.add(addressAndLocation.getString("state"));
fromGPointJSON.add(addressAndLocation.getString("from"));
latGPointJSON.add(reverseGeocoderLatLong(addressGPointJSON.get(i) + ", " + cityGPointJSON.get(i) + ", " + stateGPointJSON.get(0), true));
longGPointJSON.add(reverseGeocoderLatLong(addressGPointJSON.get(i) + ", " + cityGPointJSON.get(i) + ", " + stateGPointJSON.get(0), false));
currentLoadAddressLocations.add(i,
new String[]{
fromGPointJSON.get(i),
addressGPointJSON.get(i),
locationGPointJSON.get(i),
cityGPointJSON.get(i),
stateGPointJSON.get(i),
latGPointJSON.get(i),
longGPointJSON.get(i)
});
} // end of for loop
} // end of try catch block
catch(JSONException e){
e.printStackTrace();
}
Currently, the code gives me back the data structure that I need, a String[] of the form
["2017-03-30 21:00:00", "Address example 123", "Location Example", "CITY", "STATE", "lat", "long"]
repeated depending on how many stops where in the JSON object that was returned. I need to find a way to sort the first value of the array from top to bottom inside the currentLoadAddressLocations array by time, so if one of the dates is "2017-03-30 15:00:00" and the other is "2017-03-30 14:00:00" then the one that is before takes precedence and moves the date to the top of the currenLoadAddressLocations array while at the same time araging the second one to be below. I am having a hard time trying to find a method of doing so. Currently I know that I can compare dates if I parse the dates as:
Date from = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US).parse("2017-03-30 21:00:00");
But do not know how to work around this issue while looping through the currentLoadAddressLocations List. Further more, I do not know how to access the values in order to compare them. I can loop through the selection by using
for(String[] array: currentLoadAddressLocations){
for(String s: array){
Log.i(TAG,"ITEM: " + s);
}
}
But since they are inside a String array they cannot be changed into a date format unless I change them and then parse them back to strings.
Any suggestions will be greatly appreciated.
The answer is you should convert your String[] into a AddressDateLocation class array. Once you do that, it will be much easier to sort you data the way you want
public class AddressDateLocation implements Comparable<AddressDateLocation> {
Date date;
String address;
String location;
public void setDate(Date d) {}
public Date getDate() ...
public void setLocation(String loc) ...
public String getLocation() ...
public void setAddress(String addr) ...
public String getDate() ...
public int compareTo(AddressDateLocation other) ...
}
The data structure you need is likely not an array of String's, unless the order of the pieces ends up in a public API. You'd better keep the information in the native JSONObject, that has Map semantics. Then you can simply order by timestamp with:
List<JSONObject> currentLoadAddressLocations = TODO(/* implement this */);
currentLoadAddressLocations.sort((o1, o2) -> {
return o1.getString("date").compareTo(o2.getString("date"))
});
Note: the date format suggested in the question makes it possible to compare timestamps using their textual representation.
You could make the dates into LocalDateTime objects and use the compareTo method.
I would use the List#sort function like so:
currentLoadAddressLocations.sort((sa1, sa2) -> { // sa = String Array
try {
String pattern = "yyyy-MM-dd HH:mm:ss";
return new SimpleDateFormat(pattern, Locale.US).parse(sa1[0])
.compareTo(new SimpleDateFormat(pattern, Locale.US).parse(sa2[0]));
} catch (ParseException e) {
// If your dates are all valid you shouldn't come here.
e.printStackTrace();
return -1; // move all parse ParseExceptions to the first positions
}
});

Format conversion in java using arraylist

I am using one ArrayList which is as follow:
(A,Start,2),(A,End,7),(B,End,3),(C,Start,8),(C,End,4).
I want to convert above ArrayList into below format.
A,(2,7)
B,(0,3)
C,(8,4)
public Set<Demand> DemandData(){
ArrayList<Demand> Demanddata = new ArrayList<Demand>();
Demanddata=LoginDAO.getDemandData();
Set<Demand> dListUnique = new HashSet<Demand>(Demanddata);
for(Demand di:dListUnique){
for(Demand dj:Demanddata){
if(di.getSeatJRSS().equals(dj.getSeatJRSS())){
String data = "";
// I tried here
}
}
}
return dListUnique;
}

List of timestamps overrides the previous timestamp

I am using an arraylist to store list of timestamps of past 5 weeks.
i.e., if today is 2014-06-09, I want to store
2014-06-02
2014-05-26
2014-05-19
2014-05-12
2014-05-05
Here is my code.
public class Test {
public static void main(String ap[]) throws InterruptedException{
List<Timestamp> ts = new ArrayList<Timestamp>();
Timestamp t = new Timestamp(new java.util.Date().getTime());
Timestamp temp = null;
for(int i=0;i<5;i++){
t.setTime(t.getTime()-(7*24 * (long)60* (long)60) * (long)1000);
temp = t;
System.out.println(t);
ts.add(temp);
temp = null;
}
}
}
But the problem is always I am getting the list of overrided values i.e., list contains all the elements as last timestampI i.e 2014-05-05)
Can anybody reply to this question?
The reason you're not getting "new" timestamps is because you keep overriding the same one and adding it to the list - so you end up with the same object entered 5 times to the list and the last value will display in "all" the items. You don't need temp - simply create a new Timestamp object and add it to the list:
List<Timestamp> ts = new ArrayList<Timestamp>();
Timestamp t = new Timestamp(new java.util.Date().getTime());
for(int i=0;i<5;i++){
t.setTime(t.getTime()-(7*24 * (long)60* (long)60) * (long)1000);
System.out.println(t);
ts.add(new Timestamp(t.getTime()));
}

Trying to get the arraylist value inside hashmap key

I'm probably being stupid here...but I need help with this one! Basically i need to do a .contains("message") to determine if the key already contains the incoming message.
Thanks in advance!
EDIT: Just as a note, i do not want it to do anything if it already exists! Currently its not adding it to the list.
EDIT2: the date will not matter for the incoming message because the incoming message does not have the date portion.
private Map<Integer,List<String>> map = new HashMap<Integer,List<String>>();
public synchronized void addToProblemList(String incomingMessage, int storeNumber){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String formattedDate = sdf.format(date);
if(map.get(storeNumber)==null){
map.put(storeNumber, new ArrayList<String>());
}
for(String lookForText : map.get(storeNumber)){
if(lookForText.contains(incomingMessage)){
}else if(!lookForText.contains(incomingMessage)){
map.get(storeNumber).add(incomingMessage+"\nTime of incident: "+formattedDate+"\n--------------------------------------------------------");
}
}
}
It used to look like this, but it always added it:
public synchronized void addToProblemList(String incomingMessage, int storeNumber){
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String formattedDate = sdf.format(date);
if(map.get(storeNumber)==null){
map.put(storeNumber, new ArrayList<String>());
}
if(map.get(storeNumber).contains(incomingMessage)==true){
//Do nothing
}
if (map.get(storeNumber).contains(incomingMessage)==false){
map.get(storeNumber).add(incomingMessage+"\nTime of incident: "+formattedDate+"\n--------------------------------------------------------");
}
What you are adding to the list is a key of the store number and an empty array list,
So the first message for the store you add to the list is empty, therefore your for loop will not execute as it has no elements to iterate.
So add this
if(map.get(storeNumber)==null){
ArrayList<String> aList = new ArrayList<String>();
aList.add(incomingMessage+"\nTime of incident: "+formattedDate+"\n--------------------------------------------------------");
map.put(storeNumber, aList);
}
Note map.get(storeNumber).contains(incomingMessage)==true you dont need to boolean comparison here as contains() returns a boolean.
The reason this original approach of yours wouldn't have worked is doing a List.contains() means you are doing an check to see if the list contains an exact matching string which it would not have since when you have added the String it also contained "\nTime of incident: "+formattedDate+"\n... which I suspect would not have matched just incomingMessage
You have this:
for(String lookForText : map.get(storeNumber)){
if(lookForText.contains(incomingMessage)){
}else if(!lookForText.contains(incomingMessage)){
map.get(storeNumber).add(incomingMessage+"\nTime of incident: "+formattedDate+"\n--------------------------------------------------------");
}
}
Try this instead:
List<String> messages = map.get(storeNumber);
if(!messages.contains(incomingMessage)){
map.get(storeNumber).add(incomingMessage+"\nTime of incident: "+formattedDate+"\n--------------------------------------------------------");
}

Categories