Search code examples
javazip

How to interate ZipFile content in alphabetic order?


I have a large .zip archive with thousands of files. How can I iterate them in a specific order (eg alphabetic ascending)?

try (ZipFile zip = new ZipFile(archive)) {
    Enumeration<? extends ZipEntry> entries = zip.entries();
    while (entries.hasMoreElements()) {
        var file = entries.nextElement();
        //...
    }
}

I found streaming could be an option. But is it possible also without streaming?

List<? extends ZipEntry> list = zip.stream()
        .sorted(Comparator.comparing(ZipEntry::getName))
        .collect(Collectors.toList());

Solution

  • There is no ZipFile specific way of sorting the ZipFile's entries or "reading" the ZipFile's content ordered. The only reference to ordering in the ZipFile Javadoc is when using ZipFile.stream.

    In that case the entries "[...] appear in the Stream in the order they appear in the central directory of the ZIP file."

    So you are left with the usual approaches when ordering/sorting in java:

    Either use the stream() method to fetch a stream, order it and do your logic:

    zip.stream()
       .sorted( Comparator.comparing( ZipEntry::getName ) ) // define your order
       .forEach( this::doStuff ); // do your logic, in this example it is a method in this class
    

    or convert the enumeration to a collection and sort the collection, for example like

    List< ? extends ZipEntry > entries = Collections.list( zip.entries() );
    entries.sort( Comparator.comparing( ZipEntry::getName ) ); // define your order
    for (ZipEntry entry : entries) {
        doStuff(entry);
    }