participate


New To Java - Find strings in a list using startsWith?
<<   Back to Forum  |   Give us Feedback
10 Duke Stars rewarded for this thread
This topic has 16 replies on 2 pages.    1 | 2 | Next »
jojololo
Posts:11
Registered: 11/6/09
Find strings in a list using startsWith?   
Nov 9, 2009 11:36 AM

 
Hi I hope someone can help me with this problem. Before I start, my apologies as I am a student still trying to learn Java and have got to the murky ground of data structures.To help me better understand this I tried a sample program (which surprisingly was working fine til now ha). So I have a list of songs by various artists added to a tree which begins with the singers name. I want to be able to isolate songs by a particular artist but have tried loads of different ways of doing it to no avail. I tried creating a new list but couldn't add my songs to it. I then found the remove() method and thought why not just find what I want and remove the rest from the list I can always recreate my list again after. So I think I'm close with my code and that's it's maybe a casting issue??

String song = songTree.getElement(currentNode);

List<String> list = MyCollection.getSongs(song);
// List newList = new ArrayList();
String check = new String("Pearl Jam");
Iterator myIter = list.iterator();

while (myIter.hasNext()){

if (myIter.next().!startsWith(check)){

// newList.add();

else{

list.remove();
}
}

Edited by: jojololo on Nov 9, 2009 11:35 AM
 
endasil
Posts:2,762
Registered: 10/12/07
Re: Find strings in a list using startsWith?   
Nov 9, 2009 11:39 AM (reply 1 of 16)  (In reply to original post )

 
jojololo wrote:
Before I start, my apologies as I am a student still trying to learn Java and have got to the murky ground of data structures.
No need to apologize, as long as you are clear in your communication. Why would we be here except to help? (Well okay, to amuse ourselves...)
To help me better understand this I tried a sample program (which surprisingly was working fine til now ha). So I have a list of songs by various artists added to a tree which begins with the singers name. I want to be able to isolate songs by a particular artist but have tried loads of different ways of doing it to no avail. I tried creating a new list but couldn't add my songs to it.
Why not? What happened when you tried? This is probably the right way and should definitely work, so let's isolate the problem there.
I then found the remove() method and thought why not just find what I want and remove the rest from the list I can always recreate my list again after.
Nah that doesn't seem like a reasonable idea. Let's go back to creating a new collection to hold your isolated subset.

Post an SSCCE of your attempt at using a new list, and tell us where it goes wrong and what you expect it to do instead. Be sure to use the CODE button in the editor to format your code.
 
jojololo
Posts:11
Registered: 11/6/09
Re: Find strings in a list using startsWith?   
Nov 9, 2009 4:34 PM (reply 2 of 16)  (In reply to #1 )

 
Thanks for the quick reply (faster than I was expecting!). I commented out a bit of what was left with the add to a new list try. The end result I'm aiming for is to add them all in a particular order (the list is not sorted) to a tree so I can get a bit of practice with tree traversal techniques I'm currently studying. I'm a bit embarassed to say this is the only way I learn, by doing my own versions of the small code examples I get on my course and try and see the bigger picture. Sorry I didn't notice the code button. On the bright side I've learned something new already, had to google what SSCCE meant ha. K so here's an attempt at a cut down version of the code..
import java.util.*;
 
public class Test {
 
    public static void main(String[] args){
    	
    	List variousArtists = new ArrayList();
        // Some intentionally doubled to ensure only one gets put on the tree later            
        variousArtists.add("Pearl Jam - Even Flow");
        variousArtists.add("U2 - The End Of The World");
        variousArtists.add("The Smashing Pumpkins - Spaceboy");
        variousArtists.add("Pearl Jam - Alive");
        variousArtists.add("The Smashing Pumpkins - Quiet");
        variousArtists.add("Pearl Jam - Black");
        variousArtists.add("U2 - The End Of The World");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("U2 - One");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("The Smashing Pumpkins - Mayonaise");
        variousArtists.add("U2 - Mysterious Ways");
        variousArtists.add("The Smashing Pumpkins - ******");
        variousArtists.add("Pearl Jam - Even Flow");
        variousArtists.add("The Smashing Pumpkins - Disarm");
        variousArtists.add("U2 - One");
        variousArtists.add("The Smashing Pumpkins - Quiet");
        variousArtists.add("The Smashing Pumpkins - Mayonaise");
        variousArtists.add("Pearl Jam - Black");
        variousArtists.add("The Smashing Pumpkins - Mayonaise");
        variousArtists.add("Pearl Jam - Even Flow");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("U2 - The End Of The World");
        
        List newList = new ArrayList();
        String check = new String("Pearl Jam");
        String search;
		Iterator myIter = variousArtists.iterator();
		
		while (myIter.hasNext()){
			search = (String) myIter.next;
			if (myIter.next().startsWith(check)){
 
			newList.add(myIter);
 
			}        
    	}   
	}
}    
 
endasil
Posts:2,762
Registered: 10/12/07
Re: Find strings in a list using startsWith?   
Nov 9, 2009 4:44 PM (reply 3 of 16)  (In reply to #2 )

 
You're adding your iterator using newList.add(myIter), not the element returned by the iterator.

You can fix it like this:
while ( myIter.hasNext() ) {
   String elem = myIter.next();
   if ( elem.startsWith(... ) ) {
      newList.add(elem);
   }
}


Or far more simply, don't even use the iterator:
for ( String song : variousArtists ) {
   if ( song.startsWith(...) ) {
      newList.add(song);
   }
}


Both of these assume that you fix your List to be declared like this instead:
List<String> variousArtists = new ArrayList<String>();


If you don't make that change, you'll need to cast to a String.
 
jojololo
Posts:11
Registered: 11/6/09
Re: Find strings in a list using startsWith?   
Nov 9, 2009 5:04 PM (reply 4 of 16)  (In reply to #2 )

 
jojololo wrote:
Before I start, my apologies as I am a student still trying to learn Java and have got to the murky ground of data structures.No need to apologize, as long as you are clear in your communication. Why would we be here except to help? (Well okay, to amuse ourselves...)
To help me better understand this I tried a sample program (which surprisingly was working fine til now ha). So I have a list of songs by various artists added to a tree which begins with the singers name. I want to be able to isolate songs by a particular artist but have tried loads of different ways of doing it to no avail. I tried creating a new list but couldn't add my songs to it. Why not? What happened when you tried? This is probably the right way and should definitely work, so let's isolate the problem there.
I then found the remove() method and thought why not just find what I want and remove the rest from the list I can always recreate my list again after.Nah that doesn't seem like a reasonable idea. Let's go back to creating a new collection to hold your isolated subset.

Post an SSCCE of your atte this stagempt at using a new list, and tell us where it goes wrong and what you expect it to do instead. Be sure to use the CODE button in the editor to format your code.
Sorry didn't really answer your questions very well with my post;
I've tried so much at this stage I don't even remember what went wrong. basically in the try I posted just now the startsWith method is not recognised. I'm aware that I'm trying to compare an object reference to a string but thought I had dealt with that with my casting? I think my subset would be saved here in the new collection but again I'm missing something in the comparisment. Oh sometimes I feel like packing in the java! We do far too much theory and nowhere near enough actual coding.

import java.util.*;
 
public class Test {
 
    public static void main(String[] args){
    	
        List variousArtists = new ArrayList();
        // Some intentionally doubled to ensure only one gets put on the tree later            
        variousArtists.add("Pearl Jam - Even Flow");
        variousArtists.add("U2 - The End Of The World");
        variousArtists.add("The Smashing Pumpkins - Spaceboy");
        variousArtists.add("Pearl Jam - Alive");
        variousArtists.add("The Smashing Pumpkins - Quiet");
        variousArtists.add("Pearl Jam - Black");
        variousArtists.add("U2 - The End Of The World");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("U2 - One");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("The Smashing Pumpkins - Mayonaise");
        variousArtists.add("U2 - Mysterious Ways");
        variousArtists.add("The Smashing Pumpkins - ******");
        variousArtists.add("Pearl Jam - Even Flow");
        variousArtists.add("The Smashing Pumpkins - Disarm");
        variousArtists.add("U2 - One");
        variousArtists.add("The Smashing Pumpkins - Quiet");
        variousArtists.add("The Smashing Pumpkins - Mayonaise");
        variousArtists.add("Pearl Jam - Black");
        variousArtists.add("The Smashing Pumpkins - Mayonaise");
        variousArtists.add("Pearl Jam - Even Flow");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("U2 - The End Of The World");
        
        List newList = new ArrayList();
        String check = new String("Pearl Jam");
        String search;
        Iterator myIter = variousArtists.iterator();
		
              while (myIter.hasNext()){
	search = (String) myIter.next();
	      if (myIter.next().startsWith(check)){
 
	            newList.add(myIter);
 
       }        
     }  
   }
}    
 
jojololo
Posts:11
Registered: 11/6/09
Re: Find strings in a list using startsWith?   
Nov 9, 2009 5:17 PM (reply 5 of 16)  (In reply to #4 )

 
K that was really fast!! I messed up my reply on the last one cos I wasn't expectin it. It's late in the morning where I am and I'm making ridiculous mistakes at this stage think the saying goes can't see the leaves.... The actual code looks nothing like what I posted it's far too long to post but I originally started with declaring my List that way just stripped it down to solve my problem. But thank you very much after me spending hours you solved it in seconds!!
 
jojololo
Posts:11
Registered: 11/6/09
Re: Find strings in a list using startsWith?   
Nov 9, 2009 6:28 PM (reply 6 of 16)  (In reply to #5 )

 
Ah well spoke too soon! Incompatible types on:
String search =  myIter.next();
 
endasil
Posts:2,762
Registered: 10/12/07
Re: Find strings in a list using startsWith?   
Nov 9, 2009 7:29 PM (reply 7 of 16)  (In reply to #6 )

 
jojololo wrote:
Ah well spoke too soon! Incompatible types on:
String search =  myIter.next();
Re-read the last bit of my previous post, and this time listen to what it's saying.
 
jojololo
Posts:11
Registered: 11/6/09
Re: Find strings in a list using startsWith?   
Nov 10, 2009 9:10 AM (reply 8 of 16)  (In reply to #7 )

 
Sorry endasil but I did read it and understood what your saying but at the end of the day I'm still trying to assign an object to a string am I not? I kinda want to keep the iterator in there for practice cos I'm still only getting used to the idea of interfaces. So this is what I have, am I missing something painfully obvious?
import java.util.*;
public class Class {
 
    public static void main(String[] args){
    	
    	List <String>variousArtists = new ArrayList<String>();
        // Some intentionally doubled to ensure only one gets put on the tree later            
        variousArtists.add("Pearl Jam - Even Flow");
        variousArtists.add("U2 - The End Of The World");
        variousArtists.add("The Smashing Pumpkins - Spaceboy");
        variousArtists.add("Pearl Jam - Alive");
        variousArtists.add("The Smashing Pumpkins - Quiet");
        variousArtists.add("Pearl Jam - Black");
        variousArtists.add("U2 - The End Of The World");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("U2 - One");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("The Smashing Pumpkins - Mayonaise");
        variousArtists.add("U2 - Mysterious Ways");
        variousArtists.add("The Smashing Pumpkins - ******");
        variousArtists.add("Pearl Jam - Even Flow");
        variousArtists.add("The Smashing Pumpkins - Disarm");
        variousArtists.add("U2 - One");
        variousArtists.add("The Smashing Pumpkins - Quiet");
        variousArtists.add("The Smashing Pumpkins - Mayonaise");
        variousArtists.add("Pearl Jam - Black");
        variousArtists.add("The Smashing Pumpkins - Mayonaise");
        variousArtists.add("Pearl Jam - Even Flow");
        variousArtists.add("Radiohead - Street Spirit");
        variousArtists.add("U2 - The End Of The World");
        
        List <String>newList = new ArrayList<String>();
        String check = new String("Pearl Jam");
        Iterator myIter = variousArtists.iterator();
		
		while (myIter.hasNext()){
			String search = myIter.next();
			if (search.startsWith(check)){
 
			newList.add(search);
 
			}        
    	        }  
         }
}  
 
jojololo
Posts:11
Registered: 11/6/09
Re: Find strings in a list using startsWith?   
Nov 10, 2009 9:22 AM (reply 9 of 16)  (In reply to #8 )

 
Ok I spotted what was wrong amazing how a break away from these things can sort them out was burned out from it last night. The cast was needed afterall..

String search = (String)myIter.next();


Many thanks for all your effort I hope some day to be competent enough to help others. I'm off for some tree traversal practice (finally! ha)
 
endasil
Posts:2,762
Registered: 10/12/07
Re: Find strings in a list using startsWith?      
Nov 10, 2009 9:33 AM (reply 10 of 16)  (In reply to #9 )

 
Ah, no, the cast is not needed. I just missed a chunk. If you're still going to use the iterator (I would suggest my second example, but whatever) you need to type the Iterator as well:
Iterator<String> myIter = ...;

Then the cast isn't needed.
 
DrClap
Posts:38,747
Registered: 4/30/99
Re: Find strings in a list using startsWith?   
Nov 10, 2009 9:44 AM (reply 11 of 16)  (In reply to #10 )

 
Also, a shorter and nicer way to write this:
Iterator<String> myIter = variousArtists.iterator();
		
  while (myIter.hasNext()){
    String search = myIter.next();
    if (search.startsWith(check)){
      newList.add(search);
    }        
  }  
}
is like this:
for (String search: variousArtists) {
  if (search.startsWith(check)){
    newList.add(search);
  }        
}
 
endasil
Posts:2,762
Registered: 10/12/07
Re: Find strings in a list using startsWith?   
Nov 10, 2009 9:46 AM (reply 12 of 16)  (In reply to #11 )

 
DrClap wrote:
Also, a shorter and nicer way to write this...
That'd be the "second example" I was referencing ;-).
 
DrClap
Posts:38,747
Registered: 4/30/99
Re: Find strings in a list using startsWith?   
Nov 10, 2009 9:51 AM (reply 13 of 16)  (In reply to #12 )

 
endasil wrote:
That'd be the "second example" I was referencing ;-).

Are you kidding? That was ten posts back!
 
jojololo
Posts:11
Registered: 11/6/09
Re: Find strings in a list using startsWith?   
Nov 10, 2009 10:12 AM (reply 14 of 16)  (In reply to #13 )

 
Now, now people easy does it. Ye were both right, they both work just fine but isn't that the beauty of all this OO stuff there's many ways of doing things depending on the person, level of experience etc. The second one (which is clearly stated amongst my messed up posts) definitly looks the nicer but seemings as I don't even know what the colon is about I'll just try to stick to the little I do know. Regardless, the issue is resolved so again thanks!
 
This topic has 16 replies on 2 pages.    1 | 2 | Next »
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics
    Users Online : 62
  • Guests : 128

About Sun forums
  • Sun Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Sun Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums