Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8540261
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 11, 20262026-06-11T11:33:24+00:00 2026-06-11T11:33:24+00:00

I have 2 lists coming into my method sorted in a certain order (either

  • 0

I have 2 lists coming into my method sorted in a certain order (either ascending or descending based on an ID field)

I have a custom comparator implementation that allows me to throw both lists into the treeset and achieve the desired results.

My issue is after the treeset is loaded, I need to return a single list back from the method. My first implementation didn’t care about ordering so I did this (composite is my named TreeSet):

    composite.addAll(custom);
    composite.addAll(reference);    

    Iterator<MyObject> anIter = composite.iterator();
    ArrayList<MyObject> returnVal = new ArrayList<MyObject>();
    while(anIter.hasNext()) 
        returnVal.add(anIter.next());

Once I execute this, the two lists “custom” and “reference” are back to the default ordering. The Javadocs for Collection’s iterator() method state that will return the list in ascending order, which is likely where my trouble is coming from.

So…is there no way to return the content of a TreeSet while protecting the original list ordering? A treeset is what came to mind because I wanted to use the power of the comparator interface over the two collections to union them with addAll() and throw out the dupes.

Any suggestions on protecting the ordering would be appreciated.

EDIT*

Set<MyObject> composite = new TreeSet<MyObject>(new Comparator<MyObject>(){
        @Override
        public int compare(MyObject arg0, MyObject arg1) {
            int arg0ID = arg0.getObjID();
            int arg1ID = arg1.getObjID();                
            if(arg0ID < arg1ID) return -1;
            else if(arg0ID> arg1ID) return 1;
            else return 0;
        }           
    }); 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-11T11:33:25+00:00Added an answer on June 11, 2026 at 11:33 am

    is there no way to return the content of a TreeSet while protecting the original list ordering?

    No, of course not. TreeSet is the wrong tool for this job. The point of using a TreeSet is that it applies a Comparator-based ordering on the objects that the set contains. Use a different data structure — how about a LinkedHashSet? — if you want to remove duplicate objects while retaining insertion order.


    I don’t see how your statement refutes my decision. I intentionally CHOSE the TreeSet because I wanted to exercise the comparator interface. … My comparator let me identify what components of the object to filter on. I don’t want to lose that capability

    In a TreeSet: “The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.” You cannot pick any order ordering (particularly one like insertion ordering) with a TreeSet. If you can’t use equals() and hashCode() to pick the object fields that represent identity, use a decorate-dedup-undecorate pattern with a LinkedHashSet, where the decorator contains equals() and hashCode() implementations. Comparator/Comparable is for specifying ordering, not identity or equality.


    You’re suggesting I need to abandon it and move to something like LinkedHashSet?

    Yes, exactly. Either make MyObject implement the .equals() and .hashCode() that you mean:

    class MyObject {
        // snip
    
        @Override
        public boolean equals(Object o) {
            // boilerplate junk here
            if (!o instanceof MyObject) return false;
            MyObject other = (MyObject) o;
            return this.getObjID() == other.getObjID();
        }
    
        @Override
        public int hashCode() {
            return this.getObjID();
        }
    
        // snip
    }
    

    and dedup like so:

    List<MyObject> custom = /* snip */;
    List<MyObject> reference = /* snip */;
    
    Set<MyObject> uniques = new LinkedHashSet<>(custom.size() + reference.size());
    uniques.addAll(custom);
    uniques.addAll(reference);
    List<MyObject> deduped = new ArrayList<>(uniques);
    

    Or use the decorate–dedup–undecorate pattern that I mentioned. The decorator class would look something like this:

    class Decorator {
        private final MyObject value;
    
        public Decorator(MyObject value) {
            this.value = value;
        }
    
        public MyObject getValue() {
            return value;
        }
    
        @Override
        public boolean equals(Object o) {
            // boilerplate junk here
            if (!o instanceof Decorator) return false;
            Decorator other = (Decorator) o;
            return this.value.getObjID() == other.value.getObjID();
        }
    
        @Override
        public int hashCode() {
            return this.value.getObjID();
        }
    }
    

    and here’s roughly how you’d use it:

    List<MyObject> custom = /* snip */;
    List<MyObject> reference = /* snip */;
    
    Set<Decorator> uniques = new LinkedHashSet<>(custom.size() + reference.size());
    for (MyObject m : custom) uniques.add(new Decorator(m));
    for (MyObject m : reference) uniques.add(new Decorator(m));
    
    List<MyObject> deduped = new ArrayList<>(uniques.size());
    for (Decorator d : uniques) deduped.add(d.getValue());
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Specifically, I have two lists of strings that I'd like to combine into a
I have lists where strings correspond with values. For example, in a company list
I have lists of data such as a = [1,2,3,4] b = [a,b,c,d,e] c
I have lists of variable length where each item can be one of four
Just some example code here, but I have lists of strings that I want
I use massive.cs as a DAL, but I create Models that have Lists for
i have three lists with the same number of elements in each other, i
I have a lists: my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456', 'def-111', 'qwe-111'] bad =
I have 2 lists in excel. First one is for searching (i want to
I have two Lists of dictionaries. Both are not not null. How to merge

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.