java - Sort a List by attribute but keep order of same attributes -


i have list this:

{a[1], a[2], b[1], a[3], b[2], b[3], a[4]}

whereas a,b attribute of object in list.
numbers indicate the order of objects related each other same attribute.


now, want sort list have following result:

{a[1],a[2],a[3],a[4],b[1],b[2],b[3]}


in concrete, means order of objects related each other object same attribute should stay same, general order should attribute. problem order related each other not determinable additional attribute, specified order in root list.

how this?

just use list.sort method sort elements based on attribute value.

elements same attribute value remain in same order have been inserted.

for instance:

@test public void testsortlist() {      list<element> list = new arraylist<>();     list.add(new element("a", 1));     list.add(new element("a", 2));     list.add(new element("b", 1));     list.add(new element("a", 3));     list.add(new element("b", 2));      list.sort((element1, element2) -> element1.getvalue().compareto(element2.getvalue()));      assertthat(list.get(0).getvalue()).isequalto("a");     assertthat(list.get(0).getposition()).isequalto(1);     assertthat(list.get(1).getvalue()).isequalto("a");     assertthat(list.get(1).getposition()).isequalto(2);     assertthat(list.get(2).getvalue()).isequalto("a");     assertthat(list.get(2).getposition()).isequalto(3);     assertthat(list.get(3).getvalue()).isequalto("b");     assertthat(list.get(3).getposition()).isequalto(1);     assertthat(list.get(4).getvalue()).isequalto("b");     assertthat(list.get(4).getposition()).isequalto(2); } 

where element class looks follow:

class element {    /** attribute used sort elements */   private string value;    /** attribute used remember original position of element in list */   private int position;    public element(string value, int position) {     this.value = value;     this.position = position;   }    public string getvalue() {     return value;   }    public int getposition() {     return position;   }    /** insert equals , hashcode! */ } 

Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -