在一个对象中具有相同引用的列表对象

时间:2016-08-26 20:12:51

标签: java

我需要在一个具有相同引用的对象中对具有相同引用的列表的对象进行分组,并且其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;
    }
}

1 个答案:

答案 0 :(得分:0)

做你想做的事就是这样的

    // 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