对列表进行排序取决于另一个排序列表,该列表具有一个用于排序的共同属性

时间:2017-07-26 10:36:43

标签: java list sorting arraylist collections

很抱歉有很长的描述,但我试图准确地解释内容,

我有两个不同对象的列表,例如

class Company {
     int id;
     String name;
     /* getters and setters */
}

class CompanyBySupplier {
     String nameId;
     Long stakeValue;
     Long incomeValue;
     /* getters and setters */
}

这些列表中的公共属性是公司的idnameId的{​​{1}}

CompanyBySupplierlistToSort的对象列表,CompanyBySuppliersortedList的对象列表,

Company

如果您发现List<CompanyBySupplier> listToSort = {["ID3,546456,56464"],["ID4",4565,456456],["ID1,1234,2345"],["ID2",4335,34535],["ID5,345,546"]} List<Company> sortedList = {["ID1","A"],["ID2","B"],["ID3","C"],["ID4","D"],["ID5","E"]} 已根据我想要间接为sortedList执行的名称属性进行了排序。

这意味着,我需要lisToSort的顺序listToSortsortedList id Company nameId

所以预期的输出应该是,

CompanyBySupplier

因为ID1,ID2,ID3,ID4,ID5是公司的sortedList中的顺序。

我能想到的是通过比较两个列表的id和nameid创建一个新列表,这两个列表将包含新类型的对象,例如,

list listToSort = {["ID1,1234,2345"],["ID2",4335,34535],["ID3,546456,56464"],["ID4",4565,456456],["ID5,345,546"]}

并在actualCompanyName上使用Comparator来解决我的问题。 但我很想知道还有其他更好的方法吗

1 个答案:

答案 0 :(得分:1)

您的排序列表已经在Id的基础上排序。您可以在相同ID的基础上对第二个列表进行排序。

List<CompanyBySupplier> listToSort = new List<CompanyBySupplier> { new CompanyBySupplier() { nameId = "ID3", stakeValue = "546456", incomeValue = "56464" }, new CompanyBySupplier() { nameId = "ID4", stakeValue = "546456", incomeValue = "56464" }, new CompanyBySupplier() { nameId = "ID2", stakeValue = "546456", incomeValue = "56464" }, new CompanyBySupplier() { nameId = "ID1", stakeValue = "2345", incomeValue = "2346" } };
                List<Company> sortedList = new List<Company>() { new Company(){ id = "ID1", name = "A" }, new Company() { id = "ID2", name = "B" }, new Company() { id = "ID3", name = "C" } };


                listToSort.Sort(delegate(CompanyBySupplier x, CompanyBySupplier y) 
                {
                    return x.nameId.CompareTo(y.nameId);
                });

                foreach (var item in listToSort)
                {

                    Console.WriteLine(item.nameId);
                }
                Console.ReadKey();
            }
        }

        public class Company
        {
            public string id { get; set; }
            public string name { get; set; }
        }

        public class CompanyBySupplier
        {
            public String nameId;
            public string stakeValue;
            public string incomeValue;
        }