One option is to use Map<String, Integer> , where the keys represent individual lines, and the map value is a counter for each of them.
So you can do something like:
Map<String, Integer> stringsWithCount = new TreeMap<>(); for (String item : str) { if (stringsWithCount.contains(item)) { stringsWithCount.put(item, stringsWithCount.get(item)+1)); } else { stringsWithCount.put(item, 0); } }
And then you can iterate the map upon completion:
for (Entry<String, Integer> entry : stringsWithCount.entrySet()) {
and create a row of results.
It was like an old school implementation; if you want to be fantastic and surprise your teachers, you can go for a Java8 / lambda / stream solution:
Arrays.stream(str) .collect(Collectors .groupingBy(s -> s, TreeMap::new, Collectors.counting())) .entrySet() .stream() .flatMap(e -> Stream.of(e.getKey(), String.valueOf(e.getValue()))) .collect(Collectors.joining())
But, of course, you should be able to explain this piece of code.
source share