0

For example, To select only audios from list of files which has audio, video, image etc., I'm using following code.

private void selectAllAudio() {
    for(Entity entity: entities){
        if(entity.getItemType() == ItemType.Audio){
            entity.setSelected(true);
        }
    }
}

The above code will loop all 1000's of items where only 100 items are audio. So I just want to know is there any better way to select all audios instead of looping all files.

Gunaseelan
  • 14,415
  • 11
  • 80
  • 128

2 Answers2

2

If the iterating is a bottleneck, then you could use different data structures. You could maintain a separate collection just for the ItemType.Audio items. You could also maintain a Map in which the key is the ItemType. Both options would allow for quickly accessing just the items you're interested in.

jspcal
  • 50,847
  • 7
  • 72
  • 76
0

Well, I don't see any workarounds here.
As far as I understand your question, you have this entity object which is "fixed" (meaning that either you already have it at runtime or you query somehow some object and get that object as a result).
As you stated in the comments, since you have Java 7 the only way of achieving that is via a normal for loop
If you're coming from Java 8 onwards, then this would be another way

private void selectAllAudio() {
entities.stream().filter (s -> entity.getItemType() == ItemType.Audio).peek(object -> object.setSelected(true)).toList(Entity::new);
}
//Use the toList() method only if you then need a List of all Audio Objects


Asymptotically speaking, streams and normal iterations should take the same time but, if efficiency in terms of Big O is what you're looking for, you might want to consider other Data Structures (ie, basic operations on hashset are, most of the time, constants while this is not always true for Lists).
Note that there are libraries (like this one, though its last update was 4yrs ago) for Java 7 that implements somehow the Lambda Expressions and Streams of Java 8 but, of course, we're not talking about the same thing... :)

Gianmarco F.
  • 780
  • 2
  • 12
  • 36