0

Got stuck in the following problem. I populated a ArrayList from the database which is as below. But found that I need to group the list based on names (if the other two values in the first list match with second list) . And after grouping, I need to sort the names in ascending order. I am unable to find a solution to this. How should I iterate it, group and sort names?

VerDetail (0)

Date : Aug 3,2016 Type : Income Name : Tom

VerDetail (1)

Aug 3,2016 SSN Tom

VerDetail (2)

Aug 3,2016 Income Ben

VerDetail (3)

Aug 3,2016 SSN Ben

VerDetail (4)

Aug 3,2016 Income Jack

VerDetail (5)

Aug 3,2016 SSN Jack

I want my list to be grouped on names as below,

VerDetail (0)

Aug 3,2016 Income Ben Jack Tom

VerDetail (1)

Aug 3,2016 SSN Ben Jack Tom

Tom Morris
  • 385
  • 1
  • 4
  • 12

1 Answers1

0

By using sort() method of collection, you can sort it by grouping.

public class SortTest {

    @Test
    public void test() {
        List<Integer> list = new ArrayList<Integer>();
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(4);
        list.add(1);

        System.out.println("Unsorted: " + list);

        Collections.sort(list);

        System.out.println("Sorted: " + list);
    }

}

Output:

Unsorted: [1, 2, 3, 4, 1] 
Sorted: [1, 1, 2, 3, 4]

Resource Link: How to group elements in ArrayList<CustomObject>


In Java 8

Using the Collectors class and streams, you can do this :

Map<String, List<Person>> mapByName = allPeople.stream()
                                               .collect(Collectors.groupingBy(Person::getName));

Resource Link: Group by field name in Java

Community
  • 1
  • 1
SkyWalker
  • 28,384
  • 14
  • 74
  • 132