Java 8 – Stream Collectors groupingBy
Java 8 – Stream Collectors groupingBy
Grupowanie danych zrealizować można z użyciem klasy Collectors i metody groupingBy:
import static java.util.stream.Collectors.groupingBy;
Załóżmy, że posiadamy klasę która przechowuje kod Ascii dla litery przekazanej w konstruktorze:
class AsciiLetter { int item; public AsciiLetter(int item) { this.item = item; } public int getItem() { return item; } public void setItem(int item) { this.item = item; } }
Posiadamy również listę obiektów:
List<AsciiLetter> items = Arrays.asList( new AsciiLetter('a'), new AsciiLetter('b'), new AsciiLetter('c'), new AsciiLetter('d'), new AsciiLetter('d'));
Cel to zgrupowanie danych w taki sposób aby otrzymać mapę gdzie kluczem jest kod Ascii dla danej litery a wartością lista obiektów o takim samym kodzie Ascii:
Map<Integer, List<AsciiLetter>> result = items.stream().collect(groupingBy(letter -> letter.getItem())); System.out.println(result);
Wynik:
{ 97=[pl.javaleader.streamCollectorsGroupingBy.Letter@3feba861], 98=[pl.javaleader.streamCollectorsGroupingBy.Letter@5b480cf9], 99=[pl.javaleader.streamCollectorsGroupingBy.Letter@6f496d9f], 100=[pl.javaleader.streamCollectorsGroupingBy.Letter@723279cf,pl.javaleader.streamCollectorsGroupingBy.Letter@10f87f48] }
Sortowanie mapy po kluczu w kolejności malejącej:
Map<Integer, List<AsciiLetter>> finalMap = new LinkedHashMap<>(); result.entrySet().stream() .sorted(Map.Entry.<Integer, List<AsciiLetter>>comparingByKey() .reversed()).forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue())); System.out.println(finalMap); }
Leave a comment