public static List groupBy(List list, Function dynamicReference) { Map> groupedStudents = list.stream() .collect(Collectors.groupingBy(dynamicReference)); return groupedStudents.values().stream() .flatMap(Collection::stream) .collect(Collectors.toList()); } public static void main(String[] args) { List students = Arrays.asList( new Student("Alice", "female", 20), new Student("Bob", "male", 22), new Student("Charlie", "male", 23), new Student("Alice", "female", 21), new Student("Bob", "male", 22) ); List groupedBySex = groupBy(students, Student::getSex); List groupedByAge = groupBy(students, Student::getAge); System.out.println(Arrays.toString(groupedBySex.toArray())); System.out.println(Arrays.toString(groupedByAge.toArray())); }