C# OfType in Java Android

104 views Asked by At

I'm writing an app using iText 5G, I have seen a piece of code to doesn't allow that tables split at page end but that code was written in C#, I have converted almost of all the code to Java but I'm stuck in one line that I don't know the equivalent in Java.

The C# code:

public override IList<iTextSharp.text.IElement> End(iTextSharp.tool.xml.IWorkerContext ctx, iTextSharp.tool.xml.Tag tag, IList<iTextSharp.text.IElement> currentContent)
{
    string keeprowstogetherattr = "keeprowstogether";
    var retval = base.End(ctx, tag, currentContent);
    if (tag.Attributes.ContainsKey(keeprowstogetherattr) && tag.Attributes[keeprowstogetherattr] == "true")
    {
        foreach (PdfPTable table in retval.OfType<PdfPTable>())
        {
            table.KeepRowsTogether(0);
        }
    }
    return retval;
}

My Java code at the moment:

public List<Element> End(WorkerContext ctx, Tag tag, List<Element> currentContent)
{
    {
        String keeprowstogetherattr = "keeprowstogether";
        List<Element> retval = super.end(ctx, tag, currentContent);
        if (tag.getAttributes().containsKey(keeprowstogetherattr) && tag.getAttributes().get(keeprowstogetherattr) == "true");
        {
            for (PdfPTable table : retval.OfType<PdfPTable>())
            {
                table.keepRowsTogether(0);
            }
        }
        return retval;
    }
}

The line that I'm stuck:

PdfPTable table : retval.OfType<PdfPTable>()

I don't know the equivalent to C#'s OfType in Java. Thanks.

EDIT: My min API is 19, so stream() doesn't work.

1

There are 1 answers

4
chrylis -cautiouslyoptimistic- On BEST ANSWER

If you can't use the stream filters, the simplest way is probably to do an instanceof check inside the for loop:

for(Element e: retval) {
    if(e instanceof PdfPTable) {
        ((PdfPTable) e).keepRowsTogether(0);
    }
}

As stylistic notes, you should name your methods starting with lowercase letters (end), and that keeprowstogetherattr should be a constant field named KEEP_ROWS_TOGETHER_ATTR (or better yet, ATTR_KEEP_ROWS_TOGETHER) in both C# and Java.