Trying to find a more efficent way to filter files
<p>Given a list of deviceIds, I am trying to come up with a more efficient way of handling duplicates. When a duplicate is found in the deviceId list, I need to keep only the latest file and delete the others. What i've come up with so far seems to work ok, but i'm wondering if it can be made more efficient? My current method doesn't seem to scale well, for example, it processes 25,000 files in 5 seconds but takes 70 seconds for 100,000 files. Any thoughts?</p>

<pre><code>List&lt;File&gt; filteredList;
        for(int i = 0; i &lt; deviceIds.size(); i++) {
            if(i &lt; (deviceIds.size()-1) &amp;&amp; deviceIds.get(i).equals(deviceIds.get(i+1))) {
                filteredList = Lists.newArrayList(Iterables.filter(fileList, new DeviceIdFilter(deviceIds.get(i))));
                Collections.sort(filteredList, new OldestFileComparator());
                for(int t = 0; t &lt; (filteredList.size()-1); t++) {
                    filteredList.get(t).delete();
                }
            }
        }

private static class DeviceIdFilter implements Predicate&lt;File&gt; {
    private String deviceId;
    private DeviceIdFilter(final String deviceId) {
        this.deviceId = deviceId;
    }
    @Override
    public boolean apply(final File file) {
        return file.getName().contains(deviceId);
    }
}

public class OldestFileComparator implements Comparator&lt;File&gt; {
    public int compare(File filea, File fileb) {
        if (filea.lastModified() &gt; fileb.lastModified()) {
            return +1;
        } else if (filea.lastModified() &lt; fileb.lastModified()) {
            return -1;
        } else {
            return 0;
        }
    }
}
</code></pre>

<p>Edit:</p>

<p>I implemented TacticalCoders solution which worked wonderfully, processing 100,000 files in 0.60 seconds.</p>

<pre><code>    Map&lt;String, List&lt;File&gt;&gt; fileMap = new HashMap&lt;String,List&lt;File&gt;&gt;();
    String deviceId;
    List&lt;File&gt; deviceFileList;
    for(File file : fileList) {
        deviceId = getDeviceId(file.getName());
        if(fileMap.containsKey(deviceId)) {
            fileMap.get(deviceId).add(file);
        } else {
            deviceFileList = new LinkedList&lt;File&gt;();
            deviceFileList.add(file);
            fileMap.put(deviceId, deviceFileList);
        }
    }

    for (Map.Entry&lt;String, List&lt;File&gt;&gt; mapEntry : fileMap.entrySet()) {
        deviceFileList = mapEntry.getValue();
        if(deviceFileList.size() &gt; 1) {
            Collections.sort(deviceFileList, new OldestFileComparator());
            for(int t = 0; t &lt; (deviceFileList.size()-1); t++) {
                deviceFileList.get(t).delete();
            }
        }
</code></pre>
