Ich muss eine Liste von Objekten (Student) mit einem Attribut (Location) des jeweiligen Objekts gruppieren. Der Code ist wie folgt:
public class Grouping {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1726", "John", "New York"));
studlist.add(new Student("4321", "Max", "California"));
studlist.add(new Student("2234", "Andrew", "Los Angeles"));
studlist.add(new Student("5223", "Michael", "New York"));
studlist.add(new Student("7765", "Sam", "California"));
studlist.add(new Student("3442", "Mark", "New York"));
//Code to group students by location
/* Output should be Like below
ID : 1726 Name : John Location : New York
ID : 5223 Name : Michael Location : New York
ID : 4321 Name : Max Location : California
ID : 7765 Name : Sam Location : California
*/
for (Student student : studlist) {
System.out.println("ID : "+student.stud_id+"\t"+"Name : "+student.stud_name+"\t"+"Location : "+student.stud_location);
}
}
}
class Student {
String stud_id;
String stud_name;
String stud_location;
Student(String sid, String sname, String slocation) {
this.stud_id = sid;
this.stud_name = sname;
this.stud_location = slocation;
}
}
Bitte schlage mir einen sauberen Weg vor.
Dadurch wird das Studentenobjekt zu HashMap
mit locationID
als Schlüssel hinzugefügt.
HashMap<Integer, List<Location>> hashMap = new HashMap<Integer, List<Location>>();
Iterate über diesen Code und füge Studenten zur HashMap
hinzu:
if (!hashMap.containsKey(locationId)) {
List<Location> list = new ArrayList<Location>();
list.add(student);
hashMap.put(locationId, list);
} else {
hashMap.get(locationId).add(student);
}
Wenn Sie alle Schüler mit bestimmten Standortdetails wünschen, können Sie Folgendes verwenden:
hashMap.get(locationId);
dadurch erhalten Sie alle Schüler mit derselben Standort-ID.
In Java 8:
Map<String, List<Student>> studlistGrouped =
studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));
Map<String, List<Student>> map = new HashMap<String, List<Student>>();
for (Student student : studlist) {
String key = student.stud_location;
if(map.containsKey(key)){
List<Student> list = map.get(key);
list.add(student);
}else{
List<Student> list = new ArrayList<Student>();
list.add(student);
map.put(key, list);
}
}
Verwenden von Java 8
import Java.util.List;
import Java.util.Map;
import Java.util.stream.Collectors;
import Java.util.stream.Stream;
class Student {
String stud_id;
String stud_name;
String stud_location;
public String getStud_id() {
return stud_id;
}
public String getStud_name() {
return stud_name;
}
public String getStud_location() {
return stud_location;
}
Student(String sid, String sname, String slocation) {
this.stud_id = sid;
this.stud_name = sname;
this.stud_location = slocation;
}
}
class Temp
{
public static void main(String args[])
{
Stream<Student> studs =
Stream.of(new Student("1726", "John", "New York"),
new Student("4321", "Max", "California"),
new Student("2234", "Max", "Los Angeles"),
new Student("7765", "Sam", "California"));
Map<String, Map<Object, List<Student>>> map= studs.collect(Collectors.groupingBy(Student::getStud_name,Collectors.groupingBy(Student::getStud_location)));
System.out.println(map);//print by name and then location
}
}
Das Ergebnis wird sein:
{
Max={
Los Angeles=[[email protected]],
California=[[email protected]]
},
John={
New York=[[email protected]]
},
Sam={
California=[[email protected]]
}
}
Implementieren Sie SQL GROUP BY Feature in Java mit Comparator. Comparator vergleicht Ihre Spaltendaten und sortiert sie. Wenn Sie sortierte Daten beibehalten, die als gruppierte Daten aussehen, wenn Sie beispielsweise dieselben Spaltendaten haben, sortieren Sie sie nach Sortiermechanismus, wobei die gleichen Daten auf einer Seite bleiben, und suchen Sie dann nach anderen Daten, die unterschiedliche Daten sind. Dies wird indirekt als Gruppierung derselben Daten angesehen.
public class GroupByFeatureInJava {
public static void main(String[] args) {
ProductBean p1 = new ProductBean("P1", 20, new Date());
ProductBean p2 = new ProductBean("P1", 30, new Date());
ProductBean p3 = new ProductBean("P2", 20, new Date());
ProductBean p4 = new ProductBean("P1", 20, new Date());
ProductBean p5 = new ProductBean("P3", 60, new Date());
ProductBean p6 = new ProductBean("P1", 20, new Date());
List<ProductBean> list = new ArrayList<ProductBean>();
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);
list.add(p5);
list.add(p6);
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
ProductBean bean = (ProductBean) iterator.next();
System.out.println(bean);
}
System.out.println("******** AFTER GROUP BY PRODUCT_ID ******");
Collections.sort(list, new ProductBean().new CompareByProductID());
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
ProductBean bean = (ProductBean) iterator.next();
System.out.println(bean);
}
System.out.println("******** AFTER GROUP BY PRICE ******");
Collections.sort(list, new ProductBean().new CompareByProductPrice());
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
ProductBean bean = (ProductBean) iterator.next();
System.out.println(bean);
}
}
}
class ProductBean {
String productId;
int price;
Date date;
@Override
public String toString() {
return "ProductBean [" + productId + " " + price + " " + date + "]";
}
ProductBean() {
}
ProductBean(String productId, int price, Date date) {
this.productId = productId;
this.price = price;
this.date = date;
}
class CompareByProductID implements Comparator<ProductBean> {
public int compare(ProductBean p1, ProductBean p2) {
if (p1.productId.compareTo(p2.productId) > 0) {
return 1;
}
if (p1.productId.compareTo(p2.productId) < 0) {
return -1;
}
// at this point all a.b,c,d are equal... so return "equal"
return 0;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
}
class CompareByProductPrice implements Comparator<ProductBean> {
@Override
public int compare(ProductBean p1, ProductBean p2) {
// this mean the first column is tied in thee two rows
if (p1.price > p2.price) {
return 1;
}
if (p1.price < p2.price) {
return -1;
}
return 0;
}
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
}
class CompareByCreateDate implements Comparator<ProductBean> {
@Override
public int compare(ProductBean p1, ProductBean p2) {
if (p1.date.after(p2.date)) {
return 1;
}
if (p1.date.before(p2.date)) {
return -1;
}
return 0;
}
@Override
public boolean equals(Object obj) {
// TODO Auto-generated method stub
return super.equals(obj);
}
}
}
Die Ausgabe für die obige ProductBean-Liste erfolgt hier. GROUP BY-Kriterien. Hier sehen Sie die Eingabedaten, die von ProductBean in Collections.sort (Liste, Objekt des Comparator für die erforderliche Spalte) angegeben werden und Sie können die GROUPED-Daten in der Ausgabe sehen. Hoffe das hilft...
********, bevor die Gruppierung der Eingangsdaten auf diese Weise erfolgt ****** ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014] ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ******** NACH GRUPPE NACH PRODUKT_ID ****** ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014] ******** NACH GRUPPE NACH PREIS ****** ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P2 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014] ProductBean [P1 30 Mon Nov 17 09:31:01 IST 2014] ProductBean [P3 60 Mon Nov 17 09:31:01 IST 2014]
Sie können Folgendes verwenden:
Map<String, List<Student>> groupedStudents = new HashMap<String, List<Student>>();
for (Student student: studlist) {
String key = student.stud_location;
if (groupedStudents.get(key) == null) {
groupedStudents.put(key, new ArrayList<Student>());
}
groupedStudents.get(key).add(student);
}
Set<String> groupedStudentsKeySet = groupedCustomer.keySet();
for (String location: groupedStudentsKeySet) {
List<Student> stdnts = groupedStudents.get(location);
for (Student student : stdnts) {
System.out.println("ID : "+student.stud_id+"\t"+"Name : "+student.stud_name+"\t"+"Location : "+student.stud_location);
}
}
Sie können wie folgt sortieren:
Collections.sort(studlist, new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
return o1.getStud_location().compareTo(o2.getStud_location());
}
});
Vorausgesetzt, Sie haben auch den Abruf für den Standort in Ihrer Studentenklasse.
Sie könnten das tun:
Map<String, List<Student>> map = new HashMap<String, List<Student>>();
List<Student> studlist = new ArrayList<Student>();
studlist.add(new Student("1726", "John", "New York"));
map.put("New York", studlist);
die Schlüssel sind Standorte und die Werteliste der Schüler. So können Sie später eine Gruppe von Studenten erhalten, indem Sie Folgendes verwenden:
studlist = map.get("New York");
public class Test9 {
static class Student {
String stud_id;
String stud_name;
String stud_location;
public Student(String stud_id, String stud_name, String stud_location) {
super();
this.stud_id = stud_id;
this.stud_name = stud_name;
this.stud_location = stud_location;
}
public String getStud_id() {
return stud_id;
}
public void setStud_id(String stud_id) {
this.stud_id = stud_id;
}
public String getStud_name() {
return stud_name;
}
public void setStud_name(String stud_name) {
this.stud_name = stud_name;
}
public String getStud_location() {
return stud_location;
}
public void setStud_location(String stud_location) {
this.stud_location = stud_location;
}
@Override
public String toString() {
return " [stud_id=" + stud_id + ", stud_name=" + stud_name + "]";
}
}
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
list.add(new Student("1726", "John Easton", "Lancaster"));
list.add(new Student("4321", "Max Carrados", "London"));
list.add(new Student("2234", "Andrew Lewis", "Lancaster"));
list.add(new Student("5223", "Michael Benson", "Leeds"));
list.add(new Student("5225", "Sanath Jayasuriya", "Leeds"));
list.add(new Student("7765", "Samuael Vatican", "California"));
list.add(new Student("3442", "Mark Farley", "Ladykirk"));
list.add(new Student("3443", "Alex Stuart", "Ladykirk"));
list.add(new Student("4321", "Michael Stuart", "California"));
Map<String, List<Student>> map1 =
list
.stream()
.sorted(Comparator.comparing(Student::getStud_id)
.thenComparing(Student::getStud_name)
.thenComparing(Student::getStud_location)
)
.collect(Collectors.groupingBy(
ch -> ch.stud_location
));
System.out.println(map1);
/*
Output :
{Ladykirk=[ [stud_id=3442, stud_name=Mark Farley],
[stud_id=3443, stud_name=Alex Stuart]],
Leeds=[ [stud_id=5223, stud_name=Michael Benson],
[stud_id=5225, stud_name=Sanath Jayasuriya]],
London=[ [stud_id=4321, stud_name=Max Carrados]],
Lancaster=[ [stud_id=1726, stud_name=John Easton],
[stud_id=2234, stud_name=Andrew Lewis]],
California=[ [stud_id=4321, stud_name=Michael Stuart],
[stud_id=7765, stud_name=Samuael Vatican]]}
*/
}// main
}
sie können guava
s Multimaps
verwenden.
@Canonical
class Persion {
String name
Integer age
}
List<Persion> list = [
new Persion("qianzi", 100),
new Persion("qianzi", 99),
new Persion("zhijia", 99)
]
println Multimaps.index(list, { Persion p -> return p.name })
es drucken:
[qianzi: [com.ctcf.message.Persion (qianzi, 100), com.ctcf.message.Persion (qianzi, 88)], zhijia: [com.ctcf.message.Persion (zhijia, 99)]]
Function<Student, List<Object>> compositKey = std ->
Arrays.asList(std.stud_location());
studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));
Wenn Sie mehrere Objekte zur Gruppe hinzufügen möchten, fügen Sie das Objekt einfach in der compositKey
-Methode hinzu, indem Sie es durch ein Komma trennen:
Function<Student, List<Object>> compositKey = std ->
Arrays.asList(std.stud_location(),std.stud_name());
studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));