0

I'm new to Java/Android development. I need to get the specific values from my string array.

String PictureTest[] = {"a.jpg","b.png","c.txt", "d.wav", "e.tga"};

This array is diffrent every time. I need to get all values which contain .jpg, .png, .tga and form a new array with them.

System.out.println(Arrays.toString(PictureResult));
//It prints "a.jpg, b.png, e.tga"

UPD: Thanks everyone for this quick and useful responses!

1

3 Answers 3

2

Use a for loop to iterate through the elements in PictureTest[] and check if each of them contains() the extensions. Use an ArrayList or List to store the values because the size of an array cannot be modified.

String PictureTest[] = {"a.jpg","b.png","c.txt", "d.wav", "e.tga"};
ArrayList<String> PictureResult = new ArrayList<String>;

for(String item : PictureTest) {
    if(item.contains(".jpg") || item.contains(".png") || item.contains(".tga") {
        PictureResult.add(item);
    }
}

Edit: If you only need to check the file extension at the end, you can use endsWith() instead of contains().

Sign up to request clarification or add additional context in comments.

2 Comments

Would it be any better to use item.endsWith()?
@EricGuan Thanks for the suggestion! Depending on OP's requirements, endsWith() may be a better choice. I will add that to the answer...
1

In a simple way you can iterate over the original array and search for your pattern:

List<String> pictureResult = new ArrayList<String>();
for(String picture : PictureTest) {
    //use something like contains or a regex, for example
    if (picture.contains(".jpg"))
        pictureResult.add(picture);
    //etc...
}

You get the idea...

Comments

1

If you are using Java 8, you can use Predicates to filter your list. Something like this:

public class PredicateTester {

    public static void main(String args[]) {
        String PictureTest[] = {"a.jpg","b.png","c.txt", "d.wav", "e.tga"};
        List<String> filteredList = filterStrings(PictureTest, filter());
        filteredList.forEach(System.out::println);
    }

    public static Predicate<String> filter() {
        return p -> p.endsWith(".jpg") || p.endsWith(".png") || p.endsWith(".tga");
    }

    public static List<String> filterStrings (String[] fileNames, Predicate<String> predicate) {
        return Arrays.asList(fileNames).stream().filter( predicate ).collect(Collectors.<String>toList());
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.