last day (26 days later) » 

3:25 AM
0
A: Iterable Reverse For Each Loop Java

corsiKaIt should be trivial to construct a ReverseIterator<E> that takes some arbitrary Iterator<E>, traverses the whole iterator, and spits them out in reverse order. You would lose access to the real time remove() method if you did this, as you no longer have the link to it from the original Iterator...

 
Ohhh Thanks for the quick replyyyyy. I'll try this and see if this works. Thanks!
 
@Hyungjun See my update which may be of help to you.
 
But if they were a 'final', wouldn't it not be able to change cur and list?
the dataSnapshot.getChildren() returns an iterable, but is there a way to convert it into a ListIterator?
 
@Hyungjun yup - sorry, out of habit i make all my variables final until the compiler yells at me =)
@Hyungjun there is not, not other than simply making a list out of the snapshot, like new ArrayList<DataSnapshot>(dataSnapshot).listIterator(dataSnaps‌​hot.size()) or something weird like that. That's probably better than using my class, because it uses better, tested libraries - but still not what you want. What class is dataSnapshot?
Keep in mind that you never want list to change its reference - it should stay final. You're correct that cur needs to be non-final. =)
 
Hi,
The datSnapshot is a class in firebase that gets the data of a specific 'thing'
it isnt part of the native Java, but more of Firebase
 
3:28 AM
what class
android has stellar java apis, considering Josh Bloch was Google's chief java architect for a number of years
and he literally wrote the java collections framework lol
 
what do you exactly mean by class
im still new to java..
is that like the parent?
com.google.firebase.database.DataSnapshot
 
well, what's the line of code where you go SOMETHING dataSnapshot = new SOMETHING
 
is it this?
DataSnapshot is a class i believe
 
yes, but you have some Collection<DataSnapshot> or something
 
```databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

Iterable<DataSnapshot> snapShotIterator = dataSnapshot.getChildren();
for (DataSnapshot doc : snapShotIterator) {
BlogPost blogPost = doc.getValue(BlogPost.class);
blog_list.add(blogPost);

}
//Log.d("HomeFragment", "onCreateView: " + blog_list.size());
//Send updated list to adapter.
blogRecyclerAdapter.updatePosts(blog_list);
}
```
this is the whole class that the code is in
 
3:30 AM
oh i see
okay
and you want to iterate in reverse why?
wouldn't it be better to just get the ones you need and then apply the proper sorting to those?
because you might not be able to rely on the ordering that comes out of getChildren
there's nothing in its documentation that says something like "these are sorted by the order they're entered" or anything
 
I need to iterate in reverse because in the actual app, when the content is outputted
it outputs them in 'oldest first'
 
it might not always
 
like thats how its stored in firebase
 
when you stick them in a database and pull it out again
it might not always be in the same order
the documentation doesn't say what order they'll be in, so you should ASSUME you can't trust the ordering
is BlogPost your own class?
 
yep
 
3:34 AM
then you should consider making a Comparator<BlogPost> that does something like this
public class BlogPostSortByNewestFirst implements Comparator<BlogPost> {
public int compare(BlogPost a, BlogPost b) {
Date aa = a.getPostedDate(); // i made up postedDate, replace that
Date bb = b.getPostedDate();
return aa.compareTo(bb);
}
}
that's not perfect of course i just made itup
but something like that
and then you can just do something like
List<BlogPost> list = new ArrayList<BlogPost>();
for(DataSnapshot ds : dataSnapshot.getChildren()) list.add(ds.getValue(BlogPost.class); // i think? revisit that...
Collections.sort(list, new BlogPostSortByNewestFirst()); // sorts newest first
 
ah icic
 
making your first app? school? work? fun? just curious
 
how would i then do the blog_post.add() for this?
 
oh cool! let me tell you man, you're starting your career at an exciting time
and on the right track
 
i saw something abt coding like 2/3 years ago i believe
and i did some python
:p
 
3:42 AM
python is good - it's gaining a lot of traction
Java is still king, for now, and will be around for a long long time
but python is on the rise to be sure
 
how do collections work?
do I have to for loop through all elements and then do the blog_post.add()?
 
well how collections work is a complicated topic, i mean, there's literally books on it
and note you don't have a colecltion
you have an iterable
the DataSnapshot class is defined, according to Google's documentation, as "public class DataSnapshot extends Object"
which means it is not a collection, it's just an object
 
the collections.sort just sorts the list of blog posts right?
 
it does provide you an iterable to iterate over its children
that's correct - LIST is a collection
specifically, list an interface that expands on the collection interface
for example, if you look at the definition of list on Java's documentation, you'll see public interface List extends Collection
but you can't sort an interable, only a list
because lists have order
you might think iterables have order too, but they don't have an order you can sort
 
icic
i still dont really get how to implement that reversed list into the for each loop thogh...
 
3:50 AM
so in my original code
what i was doing was taking the blog posts out of the iteratable one at a time and adding them to the list
and i do this as soon as i make the iterable
so you'd use that like this
ReverseIterator<DataSnapshot> rev = new ReverseIterator<>(dataSnapshot.getChildren());
 
ooh icic
and use that reverse iterator into the foreach loop right?
 
right
now your rev is a drop in replacement for snapShotIterator
except it reverses it
of cousre, i've never tested that code i wrote
so take it with a grain of salt
but there's a big lesson here
and that's that you are relying on the dataSnapshot to always return them oldest first
and you should not rely on that
even though you've seen that it always does that
there's no guarantee
 
icicicici
 
it's like how if you go on a date, and you always pick up the bill
your girlfriend shouldn't rely on you always picking up the bill
she should be prepared to pay her bill JUST IN CASE you aren't paying her bill too this time
 
icic
 
3:54 AM
in fact, your professor or teacher or whatever
 
bold of u to assume i have one :p
lolol
 
they may very specifically have a test case
that adds them in the wrong order
 
ooh
ic
 
so keep what you have in blog_list
although in all honest, that is a poor name, as we don't use underscores in variable names - blogList is generally more idiomatic java
then make a comparator that sorts your blog_list
 
ic
thanks for ur time btw
 
3:56 AM
hey np
i'm trying to work on my own code, but my kids are still up and quite loud
once they go to bed i'll be able to concentrate
 
nice
ty again
:3
 
making a social network - with the goal of being an uplifting space
there's so much negativity on social media these days
 
also
im pretty sure our date is sorted as a string
for some weird reason
prolly cuz my freind, whos working on the web ver. had to do that
 
i see
 
but should the comparing work similarly
 
3:58 AM
what fields are in your BlogPost class
and is the web version java?
 
the date is shown like this
"23 September 2019"
he uses angular and js
 
i see
 
public BlogPost(String author, String url, String appAppBody, String subTitle, String title, String date) {
this.author = author;
this.url = url;
this.appAppBody = appAppBody;
this.subTitle = subTitle;
this.title = title;
this.date = date;
}
 
so you have a couple options
you could od something like `getDateAsDate()` that does something like

return new SimpleDateFormat("dd M yyyy").parse(this.date);
on your blogpost class - but then... well you're parsing the date every time
better would be to change private String date to be private String dateString
and make a private Date date
then in your constructor, you have
public BlogPost(String author, String url, String appAppBody, String subTitle, String title, String dateString) {
this.author = author;
this.url = url;
this.appAppBody = appAppBody;
this.subTitle = subTitle;
this.title = title;
this.dateString = dateString;
this.date = new SimpleDateFormat("dd M yyyy").parse(this.dateString)
}
there is a table of what all of the dd and shit mean at this link docs.oracle.com/javase/7/docs/api/java/text/…
 
icic
that would work i guess
thanks!
 
4:03 AM
yup
of course
you'll have to change getDate() to getDateString()
and getDate() to return your date
then you can make your comprator use the dates appropriately
otherwise you have to do super stupid shit
 
mhmmhm
simple date format
 
yeah - it's simple
lives up to its name
 
is in the java text
class right?
 
BE WARNED simpleDateFormat instances are not thread safe
simpleDateFormat is a class n the java.text package
 
icic
just clarifying
and date is in java.util correct?
 
4:06 AM
i hope you don't mind my minor corrections - in this profession, being precise with your words is critical and can save someone a boatload of time!!
yes - there is a java.sql.Date, do not accidentally let android stuido allow you to pick that one, make sure it's java.util.Date
 
when i do the getDate()
 
but any teacher worth their salt will ding you points for using java.sql.Date
 
it says that invalide reutrntype
 
right
it is still a String
you changed date to be a Date instead of a String
 
oh
but
 
4:08 AM
so now you must make public Date getDate() {
 
ya but that return
says it needs to be a string...
 
public Date getDate() {
return this.date;
}
yes because you currently have

public String getDate() {
return this.date;
}
i'm guessing
 
public Date getDateDate() {return dateDate;}
 
that's getDateDate
not getDate
 
ya that is what i deceded the Date one should be
and not eh string
 
4:10 AM
i see
 
*the
 
so in other words
you didn't change date at all
only added dateDate
 
mhm
 
well clearly it htinks you changed something
 
cuz i thought that owuld cause complications with displaying date
 
4:11 AM
double check your member definitions
 
nvm
i was jsut being stupid
 
you changed the member definition to Date instead of String
? :p
 
mhm
:p
 
have you had sufficient coffee to be working on this?
it's 10pm here, i'm literally about to put on a pot
 
i live in HK, the time is 12
...
not us
US*
got plenty time i belive
Iterable<DataSnapshot> snapShotIterator = dataSnapshot.getChildren();
ReverseIterator<DataSnapshot> rev = new ReverseIterator<>(dataSnapshot.getChildren());

List<BlogPost> list = new ArrayList<BlogPost>();
for(DataSnapshot ds : dataSnapshot.getChildren()) list.add(ds.getValue(BlogPost.class); // i think? revisit that...
Collections.sort(list, new BlogPostSortByNewestFirst()); // sorts newest first
would this be the stuff before the for loop?
 
4:15 AM
i gathered from your name you were somewhere in that vicinity (no offense)
 
i guess
no offense taken
from south korea
 
oh cool - my brother's wife is from SK - he learned korean just for her :p so romantic of him haha
they live in San Diego now
 
lolol
thats nice
 
i married a canadian
he's... got much warmer weather than me rofl
 
would the code implemented above work?
assuming the classes and stufa re workd aout
stuff are worked out*
 
4:17 AM
that looks right
i just deleted my post
 
would i put in list in the for loop?
 
because if your professor googles it
i don't want him seeing my post hahaa
 
lolololol
 
so that list is already in the for loop
you can't see it because formatting sucks on chat
but here's a lesson in java for loops
 
w-w-wait
so
for (DataSnapshot doc : list) {
BlogPost blogPost = doc.getValue(BlogPost.class);
blog_list.add(blogPost);

}
it aint dis?
would i jsut for loop for each elemetn in list
 
4:18 AM
no it ain't
what you need is more like this
what is blog_list
how is that defined
 
blog_list = new ArrayList<>();
 
okay thought so
Iterable<DataSnapshot> snapShotIterator = dataSnapshot.getChildren();
ReverseIterator<DataSnapshot> rev = new ReverseIterator<>(dataSnapshot.getChildren());

for(DataSnapshot ds : dataSnapshot.getChildren()) {
blog_list.add(ds.getValue(BlogPost.class)); // i think? revisit that...
}
Collections.sort(blog_list, new BlogPostSortByNewestFirst()); // sorts newest first
 
`icic
 
fixed a typo
 
it says that
REverse iterator (asdfasdf.asdfasdf.asdf.asdf.DataSnapshot) in ReverseIterator cannot be applied to (asdfasdf.asdfasdf.asdf.asdf.DataSnapshot)
 
4:24 AM
right
you have to apply it to an iterator
oh but you are
ReverseIterator<DataSnapshot> rev = new ReverseIterator<>(dataSnapshot.getChildren());
hmmmmmm
 
thats the line w/ the error
 
oh i see
because ReverseIterator takes an Iterator not an Iterable
a moment
you have ac ode formatter in your android studio right?
like it does your spaces and braces for you
 
`mhm
 
okay good
because this is SHIT code without good spaces
public class ReverseIterable<E> implements Iterable<E> {

public Iterator<E> iterator() {
return new Iterator<E>() {
private final List<E> list = new ArrayList<>();
private int cur = -1;
public ReverseIterator(Iterator<E> orig) {
while(orig.hasNext()) {
cur++;
list.add(orig.next());
}
}
public boolean hasNext() {
return cur >= 0;
}
public E next() {
return list.get(cur--);
}
}
}
}
then use it like


ReverseIterable<DataSnapshot> rev = new ReverseIterable<>(dataSnapshot.getChildren());
oh shit you need to move the constructor OUT OF the iterator and INTO the iterable
here this should work - again haven't tested shit on this
public class ReverseIterable<E> implements Iterable<E> {
private final List<E> list = new ArrayList<>();
private int cur = -1;
public ReverseIterable(Iterable<E> orig) {
for(E e : orig)
cur++;
list.add(e);
}
}

public Iterator<E> iterator() {
return new Iterator<E>() {
public boolean hasNext() {
return cur >= 0;
}
public E next() {
return list.get(cur--);
}
}
}
}
 
ic
 
4:32 AM
iterables produce iterators
iterators are bad lol
but when it's all you got
it's all you got
BUT
you DO NOT NEED a reverse iterator
if you're sorting by date
we sort because it's unreliable
so uhh ... obviously... reversing an unreliable sort is just as unreliable
 
icic
public Iterator<E> iterator() {
    return new Iterator<E>() {
        public boolean hasNext() {
            return cur >= 0;
        }
        public E next() {
            return list.get(cur--);
        }
    }
}
on here
it says that there was a semocolon expected...
semi*
 
yeah probably
after the second to last one
BUT you don't need that class
because your'e sorting by newest first
so you can literally delete ReverseIterable
 
public class ReverseIterable<E> implements Iterable<E> {
private final List<E> list = new ArrayList<>();
private int cur = -1;
public ReverseIterable(Iterable<E> orig) {
for(E e : orig)
cur++;
list.add(e);
}
}
it says e is cannot be resolved
 
yeah
delete that class
you don't want it
it solves a problem you don't have
pretend you never saw it (unless you need it years from now in a different project)
all you need is

for(DataSnapshot ds : dataSnapshot.getChildren()) {
blog_list.add(ds.getValue(BlogPost.class)); // i think? revisit that...
}
Collections.sort(blog_list, new BlogPostSortByNewestFirst()); // sorts newest first

that's it
that's how it would look in a professional's code - honestly
the lesson here is - you don't want it reversed
you want it sorted
 
Iterable<DataSnapshot> snapShotIterator = dataSnapshot.getChildren();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
blog_list.add(ds.getValue(BlogPost.class)); // i think? revisit that...
}
Collections.sort(blog_list, new BlogPostSortByNewestFirst()); // sorts newest first

//
so like this?
 
4:40 AM
well that works, but you'll get points off
your first line makes an iterable
but you never use snapShotIterator
you just don't need it
 
icic
so its just
 
both your first and second lines have dataSnapshot.getChildren()
 
class BlogPostSortByNewestFirst implements Comparator<BlogPost> {
public int compare(BlogPost a, BlogPost b) {
Date aa = a.getDateDate(); // i made up postedDate, replace that
Date bb = b.getDateDate();
return aa.compareTo(bb);
}
and
 
that looks good yes
 
for(DataSnapshot ds : dataSnapshot.getChildren()) {
                blog_list.add(ds.getValue(BlogPost.class)); // i think? revisit that...
            }
            Collections.sort(blog_list, new BlogPostSortByNewestFirst()); // sorts newest first
right?
 
4:41 AM
yes, very good
remove those comments obviously hahahha
 
also
in blogpost
unhandled exception: java.text.ParseException
for the parse
 
well that just means i fucked up my parse code
the "simple name formatter" part
you could do it the shitty way, if you wanted
 
how would i implement that?
 
String[] tokens = date.split("\\s+"); // split date string by space
int day = Integer.parseInt(tokens[0]);
int month = // look up the tokens[1] variable in a table of months
int year = Integer.parseInt(tokens[2]);
 
im lost
sorry
 
4:45 AM
then this.dateDate = new Date(date - 1900, month, day);
have you ever split strings before?
 
not really
 
"My name is corsiKa".split("\\s+") results in an array of {"My", "name", "is", "corsiKa"}
 
ooh
 
\\s+ means "any number of white spaces"
so you could also do
"My name is corsiKa"
fuck this chat haha
pretend every * is a space
"My****name********is*********corsiKa"
that would produce the same thing
 
oh ic
 
4:47 AM
if you just split it by space you'd get
 
so basically just brute forcing it right?
 
yeah
not the best idea - although probably the fastest actually
it's just ... whenever you write your own code, you open it up to bugs you never thought of
btw that date defintion should be

this.dateDate = new Date(year - 1900, month, day);
 
icic
 
aight coffee is done, i've got half a cup down
gonna step away for a bit and get some coding done on my own site :p
feel free to bounce questions
 
kk
 
4:49 AM
i just might not get back to it right away
 
ill try to do some stuff on my own
ill post questions if i need
feel free to answer them in ur own time
 
5:41 AM
doing good my dude?
@Hyungjun
 
6:03 AM
i guess
at a lesson rn so
:3
but if i do this
String[] months = {"January",
"February",
"March",
"April",
"May",
"July",
"June",
"August",
"September",
"October",
"November",
"December"};

String[] tokens = date.split("\\s+"); // split date string by space
int day = Integer.parseInt(tokens[0]);

for (int i = 0; i < 12; i++) {
if (tokens[1].equals(months[i])) {
int month = i+1;
}
}


int year = Integer.parseInt(tokens[2]);

this.dateDate = new Date(year - 1900, month, day);
it says cannot resolve symbol month
 
 
2 hours later…
8:18 AM
you're defining month INSIDE the for loop
you must start by saying

int month = -1;
then
for(int i = 0; i < 12; i++) {

if(tokens[1].equals(months[i]) {
month = i; // don't do i+1 - in the Date spec, January is 0, December is 11!!
break; // no need to search the rest of the array
}
}
if(month < 0) throw new IllegalStateException("Given a month that does not exist: " + tokens[1]);
 
9:17 AM
oooh
icic
thankts a lot!
have a good night...
sorry to bother you, but the app crashes
and im not sure if its because of the stuff i changed
but if i send u a github link or something
could you in theory be able to check on it?
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.util.Date.compareTo(java.util.Date)' on a null object reference
i think this is the error
here is the github repo
 
 
8 hours later…
5:04 PM
BlogPost.java line 31, you have month = i+1; and it needs to be month = 1
looks like you have a null in your blog post list judging by the error
for(DataSnapshot ds : dataSnapshot.getChildren()) {
BlogPost bp = ds.getValue(BlogPost.class);
if(bp != null) {
blog_list.add(bp);
}
}
@Hyungjun
the above code should be in homefragment around like 97
 

  last day (26 days later) »