Inserting In a List

S

subhabangalore

Dear Group,

I am taking out the files in my desktop folder, as,

File folder = new File("C:\\Users\\subhabrata\\Desktop");

Next, I am trying to take them out one by one as using for loop and name
of each file is converted to String,

for( File name :folder.listFiles()){
String s1=name.toString();
System.out.println("####"+s1);
System.out.print( name );
}

Till this there is no issue, now I am trying to insert name of all the files in an array, generally it can be done, as,

ArrayList<String> myList = new ArrayList<String>();
myList.add(s1);

But the problem I am facing is, if I put it as,

for( File name :folder.listFiles()){
String s1=name.toString();
System.out.println("####"+s1);
System.out.print( name );
ArrayList<String> myList = new ArrayList<String>();
myList.add(s1);
}

I am getting name of files individually but I want to see them as the whole bunch like,

myList=["string1","string2","string3",...."StringN"]

My aim is to check the names then in another for loop and if match is not found with some defined name update the list.

I am slightly new in Java so if anyone can kindly suggest how I should address it.

Regards,
Subhabrata.
 
R

Roedy Green

I am getting name of files individually but I want to see them as the whole bunch like,

myList=["string1","string2","string3",...."StringN"]

you will need a loop that runs over the list and builds the combined
string.
--
Roedy Green Canadian Mind Products http://mindprod.com
Motors make noise, and that tells you about the feelings and attitudes
that went into it. Something was more important than sensory pleasure --
nobody would invent a chair or dish that smelled bad or that made horrible
noises -- why were motors invented noisy? How could they possibly be
considered complete or successful inventions with this glaring defect?
Unless, of course, the aggressive, hostile, assaultive sound actually served
to express some impulse of the owner.
~ Philip Slater (born: 1927 age: 85)
The Wayward Gate: Science and the Supernatural
 
A

Arved Sandstrom

Dear Group,

I am taking out the files in my desktop folder, as,

File folder = new File("C:\\Users\\subhabrata\\Desktop");

Next, I am trying to take them out one by one as using for loop and name
of each file is converted to String,

for( File name :folder.listFiles()){
String s1=name.toString();
System.out.println("####"+s1);
System.out.print( name );
}

Till this there is no issue, now I am trying to insert name of all the files in an array, generally it can be done, as,

ArrayList<String> myList = new ArrayList<String>();
myList.add(s1);

But the problem I am facing is, if I put it as,

for( File name :folder.listFiles()){
String s1=name.toString();
System.out.println("####"+s1);
System.out.print( name );
ArrayList<String> myList = new ArrayList<String>();
myList.add(s1);
}

I am getting name of files individually but I want to see them as the whole bunch like,

myList=["string1","string2","string3",...."StringN"]

My aim is to check the names then in another for loop and if match is not found with some defined name update the list.

I am slightly new in Java so if anyone can kindly suggest how I should address it.

Regards,
Subhabrata.
This comes up every so often. Guava and Apache StringUtils have
join-type methods for concatenating list elements with a delimiter of
your choice.

Fact is, though, if you just want a readable debugging print of your
List, did you not simply try

System.out.println(myList);

AHS
 
S

Stefan Ram

for( File name :folder.listFiles()){
String s1=name.toString();
System.out.println("####"+s1);
System.out.print( name );
ArrayList<String> myList = new ArrayList<String>();
myList.add(s1);
}

I see two answers in this NG both not mentioning what is
sticking out like a sore thumb from this code: The line

ArrayList<String> myList = new ArrayList<String>();

is within the for-loop, while it obviously should appear in
front of it. (There might be other issues I am not aware of,
but this one I saw immediately.)
 
A

Arved Sandstrom

I see two answers in this NG both not mentioning what is
sticking out like a sore thumb from this code: The line

ArrayList<String> myList = new ArrayList<String>();

is within the for-loop, while it obviously should appear in
front of it. (There might be other issues I am not aware of,
but this one I saw immediately.)
You've got a point there. :) Well, many pairs of eyes in a review is
always better than one.

AHS
 
J

Joerg Meier

I am taking out the files in my desktop folder, as,

I am getting name of files individually but I want to see them as the whole bunch like,
myList=["string1","string2","string3",...."StringN"]

You need to move the list assignment out of the loop, like so:

final File folder = new File("G:\\Media\\TV Show");
final ArrayList<String> myList = new ArrayList<String>();
for (final File name : folder.listFiles()) {
final String s1 = name.toString();
System.out.println("####" + s1);
System.out.print(name);
myList.add(s1);
}

Otherwise, you create a new, empty list for every file name, and delete the
previous one.

You can then print out your list like so:

System.out.println(myList);

Which is really short hand for the more generic version:

System.out.println(Arrays.toString(myList.toArray()));
My aim is to check the names then in another for loop and if match is not found with some defined name update the list.

It's really not clear to me what you mean by that. You will need to restate
it or explain it in more detail.

Liebe Gruesse,
Joerg
 
S

Steven Simpson

for( File name :folder.listFiles()){
String s1=name.toString();
System.out.println("####"+s1);
System.out.print( name );
ArrayList<String> myList = new ArrayList<String>();
myList.add(s1);
}

(Stefan has already noted that the list must be created before the
loop. What you have here is one list created per item in the folder,
and each of these lists is discarded.)
I am getting name of files individually but I want to see them as the whole bunch like,

myList=["string1","string2","string3",...."StringN"]

(Arved and Roedy have mentioned some ways to get this, though I think
you are after something different. Read on...)
My aim is to check the names then in another for loop and if match is not found with some defined name update the list.

Your loop seems to have two purposes: 1) display all items in a certain
format; 2) build an internal List object.

Perhaps I've misinterpreted your aim, but your wish to generate a list
of names in a string with a given format leads me to think you're under
the impression that you need to display the names somehow in order to
perform the check you mention. This is not necessary (nor useful,
except for purposes of diagnosing problems). You should do the check on
the List object, not on the formatted String.

Firstly, if you must create a List, there's a quick way to create a
fixed-size one from the array provided by listFiles():

List<File> files = Arrays.asList(folder.listFiles());

Note that this is a list of File, not String; the code below does not
need a List<String>. If you really do need a List<String>, you could do
something similar with folder.list() instead of folder.listFiles().

Next, you could scan the List for a matching file. Loop over it, and
record when you find it:

boolean found = false;
for (File file : files) {
if (file.getName().equals("foo")) {
found = true;
break; // No need to go further.
}
}

However, unless you need to keep the List around for other purposes, you
could just use the array directly from listFiles():

boolean found = false;
for (File file : folder.listFiles()) {
if (file.getName().equals("foo")) {
found = true;
break; // No need to go further.
}
}

But it would be even simpler, if you're just looking for a particular
leafname (like "foo"), rather than a leafname matching a given pattern
(like anything beginning with "foo"), to create a File object
representing that name, and checking whether the file exists:

File candidate = new File(folder, "foo");
boolean found = candidate.exists();

Note that, confusingly, java.io.File represents a file name, not a file,
so 'new File(...)' does not actually create a file.
and if match is not found with some defined name update the list.

Not sure how you intend to update the List. If it's supposed to
represent the list of files in the folder, updating the List won't
create the missing file. Perhaps you want the rest of the program to
suppose it exists; I don't know.

If you really do want to update the list, you'll have to create it as
one you can resize:

List<File> files = new ArrayList<File>(Arrays.asList(folder.listFiles()));

Read this inside out:

1. listFiles(): Get the list of filenames as an array.
2. asList(): Create a 'List view' of the array.
3. new ArrayList(): Create a modifiable list with the same contents as
the array.
 
R

Roedy Green

myList=["string1","string2","string3",...."StringN"]


FastCat, my replacement for StringBuilder has a toCommaList that
exports a comma-separated set of strings in one long string.

see http://mindprod.com/products.html#FASTCAT
--
Roedy Green Canadian Mind Products http://mindprod.com
Motors make noise, and that tells you about the feelings and attitudes
that went into it. Something was more important than sensory pleasure --
nobody would invent a chair or dish that smelled bad or that made horrible
noises -- why were motors invented noisy? How could they possibly be
considered complete or successful inventions with this glaring defect?
Unless, of course, the aggressive, hostile, assaultive sound actually served
to express some impulse of the owner.
~ Philip Slater (born: 1927 age: 85)
The Wayward Gate: Science and the Supernatural
 
L

Lew

I am taking out the files in my desktop folder, as,

"Taking out" I understood initially as "deleting", but I gather you mean "printing" or
"displaying".

File folder = new File("C:\\Users\\subhabrata\\Desktop");

You can also use forward slashes.
Next, I am trying to take them out one by one as using for loop and name
of each file is converted to String,

If you indented properly your scope issues would be easier to see. The first block
doesn't have any, but the one further down does.
for( File name :folder.listFiles()){
String s1=name.toString();
System.out.println("####"+s1);
System.out.print( name );
}

I should think you'd use 'getPath()' or 'getName()' on the 'name' instance.
Till this there is no issue, now I am trying to insert name of all the files
in an array, generally it can be done, as,
ArrayList<String> myList = new ArrayList<String>();

That is not an array, that is a 'List'.
myList.add(s1);
But the problem I am facing is, if I put it as,

Again, proper indentation would reveal any scope issues.
for( File name :folder.listFiles()){
String s1=name.toString();
System.out.println("####"+s1);
System.out.print( name );
ArrayList<String> myList = new ArrayList<String>();
myList.add(s1);
}

Now here you have a scope issue. You create a new 'List' in each iteration, add only
one item to it, then throw it away. Nowhere do you create a 'List' that survives one
loop iteration.
I am getting name of files individually but I want to see them as the whole bunch like,

You show no code that demonstrates how you determine what "you" are "getting".

Please follow
http://sscce.org/
myList=["string1","string2","string3",...."StringN"]

In that case, declare your 'List' in a scope that survives the loop.
My aim is to check the names then in another for loop and if match
is not found with some defined name update the list.

Study "scope" and "access" in Java.
I am slightly new in Java so if anyone can kindly suggest how I should address it.

What is "slightly"?
 
M

markspace

"Taking out" I understood initially as "deleting", but I gather you mean "printing" or
"displaying".

I think he means "reading." As in he reads the file entries with these
lines of code:

Again, "take... out" for reading from an array.

To subhaba: "Iterate over" is often used to describe reading from an
array in a loop (for-loop or other loop).
 
R

Robert Klemme

Just as a matter of interest what's with all the finals

particularly

for (final File name : folder.listFiles())

Despite initial appearances this is indeed legal as the
assignment is made multiple times but from the same statement.

Given that the final keyword is, aside from a flag to the compiler for
possible optimization, largely documentary, what is the point of making
name final.

It helps avoid accidental reassignment. And it helps distinguish
unchanged from changed variables.
In fact what does peppering the code with finals do to make it easily
understandable to an inexperienced developer ?

I believe in using "final" pretty often as it will immediately indicate
which local variables are constant for a method call and which are
modified all the time. Plus, with "final" you can easier catch errors
in control flow:

final String x;

if ( someCondition() ) {
x = y.toString();
}
else {
if ( someOtherCondition() ) {
x = "foo";
}
// forgot the else branch here
x = "bar";
}

System.out.println("We got " + x);

Generally I find "finally" quite useful - apparently significantly more
useful than you do. :)

Kind regards

robert
 
E

Eric Sosman

I think he means "reading." As in he reads the file entries with these
lines of code:


Again, "take... out" for reading from an array.

To subhaba: "Iterate over" is often used to describe reading from an
array in a loop (for-loop or other loop).

Let's not give the impression that "iterate" or even "iterate
over" implies read-only activities. If it did, why would the
Iterator interface specify a remove() method? :)

Typical usage is "The code iterates over the array (or list,
or sequence, or collection), doing thus-and-such." It's the
thus-and-such part that indicates whether reading or writing (or
both, or something more complicated) is involved; iteration is
just the procedure for making the visits, not their nature.

"Iterate over the array, looking for the minimum value."

"Iterate over the array, converting all the values from
degrees to radians."

If the iteration is simple or obvious (or irrelevant) it
probably doesn't get mentioned at all: The above would likely
be "find the minimum" and "convert degrees to radians." The
main reason to mention the iteration itself would be if there's
something special or unusual about it:

"The list is sorted from smallest to largest. Iterate
backwards to output the items in descending order."

"Basic cocktail-shaker sort: Iterate over the list,
exchanging adjacent pairs of elements that are out of order.
Then make another pass, this time iterating in the opposite
direction. Repeat, alternating directions, until a pass
makes no exchanges."
 
J

Joerg Meier

Just as a matter of interest what's with all the finals

final further describes what is happening - namely, whereas "File name"
says "I'm making a local variable named name of the type File", "final File
name" says "I'm making a local variable named name of the type File,
assigning it here, and then it will always stay that". In general, I prefer
being more clear over being less clear, at the cost of being more verbose.
particularly
for (final File name : folder.listFiles())
Despite initial appearances this is indeed legal as the
assignment is made multiple times but from the same statement.

In this case, it signals that inside the loop, name is not reassigned.
Given that the final keyword is, aside from a flag to the compiler for
possible optimization, largely documentary, what is the point of making
name final.
In fact what does peppering the code with finals do to make it easily
understandable to an inexperienced developer ?

It doesn't at all. I have my IDE set to automatically make final what it
can, because I'm often lazy and forget to do it myself, and didn't even
think about it when copying the code back (as for why I put it in my IDE in
the first place, I wanted to confirm that Sysout(myList) was indeed
identical to Sysout(Arrays.toString(myList.toArray())).

So, I honestly didn't even realize that my IDE put in the finals, because
I'm so used to it by now. Didn't give it any more thought than I gave the
fact that my IDE did proper code formatting on it.

In retrospect, without an explanation, it's probably more confusing than
helpful to a newbie, so it's good that you brought the issue up.

Liebe Gruesse,
Joerg
 
E

Eric Sosman

[...]
I believe in using "final" pretty often as it will immediately indicate
which local variables are constant for a method call and which are
modified all the time. [...]

De gustibus non disputandum est, but I think "final" should
be reserved for things that *mustn't* change, and shouldn't just
be pasted on to anything that happens to remain constant in the
code's current incarnation. When considering a change to some
code I might see

Thing thing = getThing();
// ... code that doesn't happen to change `thing'

or I might see

final Thing thing = getThing();
// ... code that (obviously) doesn't change `thing'

In the first case I might think about inserting, say,

if (thing == null)
thing = fallbackThing();

.... while in the second case I wouldn't even consider it: I
would suppose that the code relied on `thing' being exactly
what getThing() had returned, perhaps in some way and for some
reason not clear to me.

But, as I said above, de gustibus.
Generally I find "finally" quite useful - apparently significantly more
useful than you do. :)

"finally" is a Godsend -- but did you mean "final"?
 
E

Eric Sosman

[...]
Its also not clear to me whether the OP is expecting some form of sorted
list of filenames. If he is expecting that, it would be best to use a
TreeMap<String> rather than an ArrayList<String> to store the filenames.

Is there a reason to prefer TreeMap (or other SortedMap) over
accumulate-disordered-and-sort-afterward?
 
A

Arne Vajhøj

I am taking out the files in my desktop folder, as,

I am getting name of files individually but I want to see them as the
whole bunch like,
myList=["string1","string2","string3",...."StringN"]

You need to move the list assignment out of the loop, like so:

final File folder = new File("G:\\Media\\TV Show");
final ArrayList<String> myList = new ArrayList<String>();
for (final File name : folder.listFiles()) {
final String s1 = name.toString();
System.out.println("####" + s1);
System.out.print(name);
myList.add(s1);
}

Just as a matter of interest what's with all the finals

particularly

for (final File name : folder.listFiles())

Despite initial appearances this is indeed legal as the
assignment is made multiple times but from the same statement.

Given that the final keyword is, aside from a flag to the compiler for
possible optimization, largely documentary, what is the point of making
name final.

In fact what does peppering the code with finals do to make it easily
understandable to an inexperienced developer ?

The performance optimization benefits of final is a myth
solid founded in how JVM's from the 1990's worked.

The generous usage of final is an attempt to make
Java a more functional language.

I don't like it. If I want to program in a functional style, then
I would pick a functional language.

Arne
 
J

Joerg Meier

[...]
Its also not clear to me whether the OP is expecting some form of
sorted list of filenames. If he is expecting that, it would be best to
use a TreeMap<String> rather than an ArrayList<String> to store the
filenames.
Is there a reason to prefer TreeMap (or other SortedMap) over
accumulate-disordered-and-sort-afterward?
I think so, yes, because none of File's list() and listFiles() methods
guarantee the order of the returned files. By using TreeMap or equivalent
the OP gets the sort for free, should it be required.

For free ? The cost is just distributed amongst the insert calls, and is
likely considerably higher than with an unsorted list that has a single
sort call once it is filled. SortedMaps are for things that need sorting
accessible before all elements are inserted, which really isn't the case
here.
I use it a lot, both for that and because accessing stored objects by key
from a TreeMap is almost certainly faster than scanning an ArrayMap
unless it contains very few objects indeed.

Java doesn't have ArrayMaps. TreeMaps are O(log(n)) for get while a HashMap
alternative would be O(1). I don't think Java includes any map with
behaviour as ill coded as what you describe. Frankly, I'm having trouble
imagining any modern language having something quite that horrible. Even
LinkedList-Map-combinations usually are backed with some sort of HashMap.

I don't mean to be rude, but it seems like you have lot of misconception
about how data structures work in anything more than school/class level
implementations.

Liebe Gruesse,
Joerg
 
A

Arne Vajhøj

It helps avoid accidental reassignment. And it helps distinguish
unchanged from changed variables.

That is a nice theory.

I am a bit skeptic about the real world benefits.

In the example provided it would simply never happen.

Arne
 
A

Arne Vajhøj

On 4/2/2013 5:06 PM, Martin Gregorie wrote:
[...]
Its also not clear to me whether the OP is expecting some form of
sorted list of filenames. If he is expecting that, it would be best to
use a TreeMap<String> rather than an ArrayList<String> to store the
filenames.
Is there a reason to prefer TreeMap (or other SortedMap) over
accumulate-disordered-and-sort-afterward?
I think so, yes, because none of File's list() and listFiles() methods
guarantee the order of the returned files. By using TreeMap or equivalent
the OP gets the sort for free, should it be required.

For free ? The cost is just distributed amongst the insert calls, and is
likely considerably higher than with an unsorted list that has a single
sort call once it is filled.

It is not that obvious to me that:

n O(1) + 1 O(nlogn) is that much faster than n log(n)
SortedMaps are for things that need sorting
accessible before all elements are inserted, which really isn't the case
here.


Java doesn't have ArrayMaps. TreeMaps are O(log(n)) for get while a HashMap
alternative would be O(1). I don't think Java includes any map with
behaviour as ill coded as what you describe. Frankly, I'm having trouble
imagining any modern language having something quite that horrible. Even
LinkedList-Map-combinations usually are backed with some sort of HashMap.

I don't mean to be rude, but it seems like you have lot of misconception
about how data structures work in anything more than school/class level
implementations.

I think Martin has a lot of experience.

But I think he got this post garbled up a bit.

As you correctly state then there are no ArrayMap. I am not even sure
what such a beast would actually do.

I also somewhat suspect that he really meant TreeSet not TreeMap as
I can not see any key value pair here.

Arne
 
E

Eric Sosman

06 PM, Martin Gregorie wrote:
[...]
Its also not clear to me whether the OP is expecting some form of
sorted list of filenames. If he is expecting that, it would be best to
use a TreeMap<String> rather than an ArrayList<String> to store the
filenames.
Is there a reason to prefer TreeMap (or other SortedMap) over
accumulate-disordered-and-sort-afterward?
I think so, yes, because none of File's list() and listFiles() methods
guarantee the order of the returned files. By using TreeMap or
equivalent
the OP gets the sort for free, should it be required.

For free ? The cost is just distributed amongst the insert calls, and is
likely considerably higher than with an unsorted list that has a single
sort call once it is filled.

It is not that obvious to me that:

n O(1) + 1 O(nlogn) is that much faster than n log(n)

By design, O() obscures all the coefficients. If you were
to say that n*log(n) and 9999999999999999999999999999*n*log(n)
are both O(n*log(n)) you would be right -- but if you were to
claim the former was not "that much faster" than the latter you
would be wrong by a factor of 9999999999999999999999999999.

... and that's the gist of my question: It seems to me likely
that the actual time to sort an ArrayList of large-ish N size will
be less than the time to build a TreeMap (BTW, Martin probably
meant TreeSet) of the same N items. Argument: The TreeSet expends
effort in keeping itself always sorted all the time, while the
ArrayList has the freedom to be disordered up until the end, and
then to impose an ordering just once. The ArrayList is asked to
present one sorted version of N items, while the TreeSet must
offer sorted versions of 1,2,3,...,N items. If the intermediate
orderings are not required, I don't see much reason to compute them.

By the way, the ArrayList will use less memory -- but both
will use O(n) in all, so who cares? :)

For this insight I will charge you only O(1) pfennigs. ;-)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top