एक विशेषता द्वारा वस्तुओं की सूची समूह: जावा


97

मुझे ऑब्जेक्ट की एक सूची (छात्र) को विशेष वस्तु के एक विशेषता (स्थान) का समूह बनाने की आवश्यकता है, कोड नीचे की तरह है,

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;

    }
}

कृपया मुझे इसे करने का एक साफ तरीका सुझाएं।


2
मूल्य के रूप में स्थान और छात्रों की सूची के रूप में स्थान के साथ एक हैशमैप।
ओमोरो

स्थान के अनुसार हल करने से आपकी समस्या हल हो जाएगी, या कुछ और है?
वारलॉर्ड

तुलनित्र का उपयोग करके प्रयास करें और स्थान के अनुसार क्रमबद्ध करें।
पीहेमेक

1
@Arlord हाँ, लेकिन अगर मुझे जानकारी की आवश्यकता हो तो आगे जा रहा हूँ, अगर मैं इसे प्राप्त कर सकता / सकती हूँ, तो छात्र बेहतर गणना कर सकते हैं
दिलकुशन महेंद्र

@Omoro कृपया आप मुझे कोड द्वारा एक सुराग दे सकते हैं, मैं हाशमैप से परिचित नहीं हूं
महेंद्र

जवाबों:


130

इससे छात्रों को कुंजी के रूप में ऑब्जेक्ट के HashMapसाथ जोड़ा जाएगा locationID

HashMap<Integer, List<Student>> hashMap = new HashMap<Integer, List<Student>>();

इस कोड पर Iterate करें और छात्रों को इसमें जोड़ें HashMap:

if (!hashMap.containsKey(locationId)) {
    List<Student> list = new ArrayList<Student>();
    list.add(student);

    hashMap.put(locationId, list);
} else {
    hashMap.get(locationId).add(student);
}

यदि आप सभी छात्र विशेष स्थान के विवरण चाहते हैं तो आप इसका उपयोग कर सकते हैं:

hashMap.get(locationId);

जो आपको सभी छात्रों को एक ही स्थान आईडी के साथ मिलेगा।


4
आपने स्थान ऑब्जेक्ट्स की एक सूची घोषित की और अगली पंक्ति में आप पिछली सूची में एक छात्र ऑब्जेक्ट जोड़ते हैं जिसे एक त्रुटि फेंकनी चाहिए।
OJVM

hashMap.get () hashMap.contanisKey () गलत होने पर वापस आता है। आप containsKey () विधि करने के लिए कॉल की बचत हो सकती है, तो आप एक स्थानीय वर में पहली hashMap.get (), स्टोर परिणाम कहते हैं, और जाँच अगर यह स्थानीय var रिक्त है
Esteve

247

जावा 8 में:

Map<String, List<Student>> studlistGrouped =
    studlist.stream().collect(Collectors.groupingBy(w -> w.stud_location));

ऐसा इसलिए है क्योंकि Studentकक्षा stud_locationको अनुकूल के रूप में निर्दिष्ट किया गया है। केवल Studentकक्षा और कोई भी वर्ग जो एक ही पैकेज में परिभाषित किया Studentजा सकता है stud_location। यदि आप public String stud_location;इसके बजाय डालते हैं String stud_location;, तो यह काम करना चाहिए। या आप एक गटर फ़ंक्शन को परिभाषित कर सकते हैं। अधिक जानकारी में cs.princeton.edu/courses/archive/spr96/cs333/java/tutorial/java/…
Eranga Heshan

32
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);
    }

}

8

जावा 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
    }

}

परिणाम होगा:

{
    Max={
        Los Angeles=[Student@214c265e], 
        California=[Student@448139f0]
    }, 
    John={
        New York=[Student@7cca494b]
    }, 
    Sam={
        California=[Student@7ba4f24f]
    }
}

इस उत्तर को प्रश्न के समान उदाहरण से चिपकाकर सुधारा जा सकता है। इसके अलावा परिणाम प्रश्न में अनुरोध किए गए वांछित आउटपुट के साथ मेल नहीं खाता है।
पिम हजेब्रोक

5

जावा 8 ग्रुपिंग कलेक्टर

संभवतः देर हो चुकी है लेकिन मुझे इस समस्या के लिए एक बेहतर विचार साझा करना पसंद है। यह मूल रूप से @Vitalii फेडोरेंको के उत्तर के समान है, लेकिन चारों ओर खेलने के लिए अधिक मुट्ठी है।

आप केवल Collectors.groupingBy()फ़ंक्शन लॉजिक के रूप में समूहीकरण तर्क को पास करके उपयोग कर सकते हैं और आपको कुंजी पैरामीटर मैपिंग के साथ स्प्लिटेड सूची मिलेगी। ध्यान दें कि प्रयोग Optionalकिया जाता है जब अवांछित NPE से बचने के लिए प्रदान की गई सूची हैnull

public static <E, K> Map<K, List<E>> groupBy(List<E> list, Function<E, K> keyFunction) {
    return Optional.ofNullable(list)
            .orElseGet(ArrayList::new)
            .stream()
            .collect(Collectors.groupingBy(keyFunction));
}

अब आप इसके साथ कुछ भी समूहीकृत कर सकते हैं । प्रश्न में यहाँ उपयोग के मामले के लिए

Map<String, List<Student>> map = groupBy(studlist, Student::getLocation);

हो सकता है कि आप जावा 8 ग्रुपिंग कलेक्टर को गाइड करना चाहते हैं


4

आप निम्नलिखित का उपयोग कर सकते हैं:

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);
    }
}

4

तुलना करने वाले का उपयोग करके जावा में SQL ग्रुप बाय फ़ीचर को लागू करें, तुलनित्र आपके कॉलम डेटा की तुलना करेगा, और इसे सॉर्ट करेगा। मूल रूप से यदि आप सॉर्ट किए गए डेटा को समूहीकृत डेटा के रूप में देखते हैं, उदाहरण के लिए, यदि आपके पास एक ही दोहराया जाने वाला कॉलम डेटा है, तो सॉर्ट मैकेनिज्म उन्हें उसी डेटा को एक तरफ रखते हुए सॉर्ट करता है और फिर अन्य डेटा जो कि डिस्मिलर डेटा है, को खोजता है। इसे अप्रत्यक्ष रूप से उसी डेटा के ग्रुपिंग के रूप में देखा जाता है।

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);
        }
    }
}

उपरोक्त उत्पाद के लिए यहाँ आउटपुट है। बीन सूची को ग्रुप बाय मानदंड से किया जाता है, यहाँ यदि आप इनपुट डेटा देखते हैं जो कि ProductBean से कलेक्शंस की सूची में दिया गया है। सूची (आपके आवश्यक कॉलम के लिए तुलनित्र की वस्तु), यह आपके तुलनात्मक कार्यान्वयन के आधार पर छाँटेगा और आप नीचे दिए गए आउटपुट में देखे गए डेटा को देख पाएंगे। उम्मीद है की यह मदद करेगा...

    ******** इस तरह के आंकड़ों को जोड़ने से पहले यह ****** है
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 सोम नवम्बर 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 सोम नवम्बर 17 09:31:01 IST 2014]
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ******** उत्पाद समूह द्वारा PRODUCT_ID ******
    ProductBean [P1 20 Mon Nov 17 09:31:01 IST 2014]
    ProductBean [P1 30 सोम नवम्बर 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 सोम नवम्बर 17 09:31:01 IST 2014]

    ******** आर्डर ग्रुप द्वारा PRICE ******
    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 सोम नवम्बर 17 09:31:01 IST 2014]
    ProductBean [P3 60 सोम नवम्बर 17 09:31:01 IST 2014]


1
नमस्ते, कृपया एक ही उत्तर को कई बार पोस्ट न करें, और कृपया बिना स्पष्टीकरण के कच्चे कोड को पोस्ट न करें कि यह कैसे काम करता है और यह ऊपर दिए गए प्रश्न में समस्या को कैसे हल करता है।
Mat

क्षमा करें मित्र, कोड को पेस्ट करने में कुछ गलती थी, क्योंकि यह कई बार हो सकता है। मैंने जो पोस्ट किया है, उसके लिए मैंने एडिट किया है। आशा है कि अब ठीक लग रहा है ???
रवि बेली

मुझे कुछ याद आ रहा है या यह कोड किसी फ़ील्ड द्वारा समूहीकृत करने के बजाय सॉर्ट कर रहा है? मैं आईडी द्वारा छांटे गए उत्पादों को देखता हूं, फिर
फंडर जूल

0

आप इस तरह से हल कर सकते हैं:

    Collections.sort(studlist, new Comparator<Student>() {

        @Override
        public int compare(Student o1, Student o2) {
            return o1.getStud_location().compareTo(o2.getStud_location());
        }
    });

मान लें कि आपके पास अपने छात्र वर्ग के स्थान के लिए भी गेट्टर है।


3
क्यों छाँटे? समस्या तत्वों को समूहित करना है!
संकल्प

0

आप ऐसा कर सकते हैं:

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);

कुंजी स्थान और छात्रों की मान सूची होगी। इसलिए बाद में आप केवल उपयोग करके छात्रों का एक समूह प्राप्त कर सकते हैं:

studlist = map.get("New York");

0

आप उपयोग कर सकते guavaहैMultimaps

@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 })

यह प्रिंट करें:

[qianzi: [com.ctcf.message.Persion (qianzi, 100), com.ctcf.message.Persion (qianzi, 88)], zhijia: [com.ctcf.message.Persion (झिझिया, 99)]]


0
Function<Student, List<Object>> compositKey = std ->
                Arrays.asList(std.stud_location());
        studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));

यदि आप अपने द्वारा समूह के लिए कई ऑब्जेक्ट जोड़ना चाहते हैं, तो आप ऑब्जेक्ट को compositKeyकॉमा द्वारा अलग करने की विधि में जोड़ सकते हैं :

Function<Student, List<Object>> compositKey = std ->
                Arrays.asList(std.stud_location(),std.stud_name());
        studentList.stream().collect(Collectors.groupingBy(compositKey, Collectors.toList()));

0
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
}
हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.