将具有相同引用的list对象分组在一个对象中



我需要将具有相同引用的列表对象分组在具有相同引用的对象中,并且其stud_locatio字段包含前一个项目的所有字段的连接。

public class Grouping {
/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    List<Entreprise> entlist = new ArrayList<Entreprise>();
    entlist.add(new Entreprise("11111", "logi", "New York"));
    entlist.add(new Entreprise("11111", "logi", "California"));
    entlist.add(new Entreprise("22222", "rafa", "Los Angeles"));
    entlist.add(new Entreprise("22222", "rafa", "New York"));
    entlist.add(new Entreprise("33333", "GR SARL", "LONDON"));
    entlist.add(new Entreprise("33333", "GR SARL", "LONDON"));
    entlist.add(new Entreprise("33333", "GR SARL", "italie"));
    entlist.add(new Entreprise("33333", "GR SARL", "Paris"));
    /*  Output should be Like below
        1111  :  logi : logi - New York
        22222 :  rafa : Los Angeles - California
        33333 :  GR SARL :   LONDON -  italie - paris */
}
class Entreprise {
    String reference;
    String stud_name;
    String stud_location;
    ENTREPRISE(String sid, String sname, String slocation) {
        this.ref = sid;
        this.stud_name = sname;
        this.stud_location = slocation;
    }
}

你可以这样做

    // Grouping
    Map<String, Set<String>> group = new HashMap<String, Set<String>>();
    for (Enterprise enterp : entlist) {
        String key = enterp.getReference().concat(":").concat(enterp.getStud_name());
        String value = enterp.getStud_location();
        if (group.containsKey(key)) {
            group.get(key).add(value);
        }
        else {
            Set<String> stud = new HashSet<String>();
            stud.add(value);
            group.put(key, stud);
        }
    }
    // Printing
    for (String id : group.keySet()) {
        String locations = "";
        for (String stud : group.get(id)) {
            locations = locations.concat("-").concat(stud);
        }
        locations = locations.replaceFirst("^\-", "");
        System.out.println(id + ":" + locations);
    }

输出为

22222:rafa:New York-Los Angeles
33333:GR SARL:Paris-italie-LONDON
11111:logi:California-New York

最新更新