2016-04-11 56 views
14

का उपयोग करके सूची में ऑब्जेक्ट्स की गणना करें गुणों का मानना ​​है कि मेरे पास Animal ऑब्जेक्ट का Arraylist है।जावा 8

class Animal{ 
    String Name;//for example "Dog" 
    String Color 
} 

मुझे क्या करना चाहते हैं, गिनती कितने अलग अलग रंग ArrayList में प्रत्येक जानवर के लिए मौजूद हैं और उन्हें एक Map<String,Integer> जहां String नाम है और Integer के लिए है में डाल दिया है: वस्तु के उस वर्ग इस तरह है विभिन्न रंगों की संख्या।

उदाहरण के लिए अगर वहाँ 4 काले कुत्तों और 1 सफेद मानचित्र के बराबर डाल मैं जानता हूँ कि यह Stream उपयोग किया जा सकता है, लेकिन मैं बाहर कैसे नहीं प्राप्त कर सकते हैं

map.put("Dog",2); 

होगा।

उत्तर

19

आप क्या करना चाहते हैं grouping operation नाम संपत्ति का उपयोग कर कुंजी के रूप में। यह आसान हिस्सा है। ट्रिकियर डाउनस्ट्रीम कलेक्टर के रूप में "अलग-अलग रंगों की गिनती" व्यक्त करना है। चूंकि जेआरई में ऐसा कोई कलेक्टर नहीं है, इसलिए हमें Set स्टोरेज का उपयोग करके एक बनाना होगा। ध्यान दें कि यहां तक ​​कि अगर कोई अंतर्निहित था, तो उसे हुड के नीचे एक समान भंडारण का उपयोग करना पड़ा। इसलिए हम रंगों को map the elements, collect them into Sets आकार पूछताछ की और finish (जो केवल अलग-अलग मान रखने का मतलब):

Map<String, Integer> map = animalStream.collect(
    Collectors.groupingBy(Animal::getName, 
     Collectors.collectingAndThen(
      Collectors.mapping(Animal::getColor, Collectors.toSet()), 
      Set::size))); 
5

यह काम करना चाहिए:

Map<String, Integer> map = animal.stream().collect(
      Collectors.groupingBy(
        Animal::getName, 
        Collectors.collectingAndThen(
          Collectors.mapping(Animal::getColor, Collectors.toSet()), 
          Set::size) 
        ) 
      ); 

यहाँ कुछ परीक्षण कोड:

public static void main(String[] args) { 
    List<Animal> animal = new ArrayList<>(); 
    animal.add(new Animal("Dog","black")); 
    animal.add(new Animal("Dog","black")); 
    animal.add(new Animal("Dog","blue")); 
    animal.add(new Animal("Cat","blue")); 
    animal.add(new Animal("Cat","white")); 

    Map<String, Integer> map = animal.stream().collect(
      Collectors.groupingBy(
        Animal::getName, 
        Collectors.collectingAndThen(
          Collectors.mapping(Animal::getColor, Collectors.toSet()), 
          Set::size) 
        ) 
      ); 

    for(Entry<String, Integer> entry:map.entrySet()) { 
     System.out.println(entry.getKey()+ " : "+entry.getValue()); 
    } 

} 

Cat : 2 
Dog : 2 

नोट: इस सवाल का जवाब इस अतः पद से प्रेरित था: https://stackoverflow.com/a/30282943/1138523

+0

आप कर सकते थे, अगर आप चाहते हैं, परीक्षण कोड के लिए मानचित्र :: foreach का उपयोग करें: map.forEach ((कुंजी, मूल्य) -> System.out। println (कुंजी + ":" + मान)); – srborlongan

+2

धन्यवाद, पता नहीं था –