-7

I wrote this method to calculating number of data usage. It receives LinkedList (historyDate)with data, then i add it to Set for avoiding duplicates and calculating key-value(data - count) in Map

 public Map<String, Integer> countCodingsByDate() {
    Set<String> dateCount = new HashSet<>(codingHistory.historyDate);
         Map<String, Integer> dateOccurence = new HashMap<>();
         for (String s : dateCount) {
             int count = 0;
             for (String a : codingHistory.historyDate) {
                 if (s.equals(a)) {
                     count++;
                 }
             }
             dateOccurence.put(s, count);
         }
         return dateOccurence;
     }

Output:

{28-11-2019=5, 29-11-2019=3}

I have a qustion - in what way and how can i rework it with stream? Thank you for an answer

Lino
  • 19,604
  • 6
  • 47
  • 65
Natali
  • 45
  • 5
  • 2
    I don't really understand your code. You are basically producing a map where every value (count) is 1. – Michael Nov 29 '19 at 14:18
  • Indeed, the question is lacking your detailed explanation of the problem and what problems you may be having with your own attempt at a solution – Hovercraft Full Of Eels Nov 29 '19 at 14:19
  • added explanation – Natali Nov 29 '19 at 14:28
  • Related, but probably not duplicates: [1](https://stackoverflow.com/questions/25441088/group-by-counting-in-java-8-stream-api), [2](https://stackoverflow.com/questions/23925315/count-int-occurrences-with-java8) – Lino Nov 29 '19 at 14:45

3 Answers3

1

Just do

Map<String, Integer> result = codingHistory.historyDate.stream()
        .collect(Collectors.toMap(date -> date, date -> 1, Integer::sum));
b.GHILAS
  • 2,273
  • 1
  • 8
  • 16
1

If you can work with a Map<String, Long> then you can use this:

public Map<String, Long> countCodingsByDate() {
    return codingHistory.historyDate.stream()
        .collect(Collectors.groupingBy(
            Function.identity(),
            Collectors.counting()
        ));
}

Note: This is the normal way to find out the occurances of a Collection. For similar questions, see: 1, 2

Lino
  • 19,604
  • 6
  • 47
  • 65
1

I recommend using Collectors.groupingBy for use case like yours.

Map<String, Long> groupedByDate = codingHistory.historyDate.stream()
   .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Michael
  • 1,044
  • 5
  • 9