I would like to separate sorted elements in list by their first char.
public static void printList(List<Miejsce> list) {
for (Miejsce miejsce : list) {
System.out.print(miejsce.getNumerMiejsca() " ");
}
}
output:
A01 A02 A03 A04 A05 A06 A07 A08 B01 B02 B03 B04 B05 B06 B07 B08 C01 C02 C03 C04 C05 C06 C07 C08 D01 D02 D03 D04...
what I want to do
A01 A02 A03 A04 A05 A06 A07 A08
B01 B02 B03 B04 B05 B06 B07 B08
C01 C02 C03 C04 C05 C06 C07 C08
D01 D02 D03 D04...
CodePudding user response:
We just need to add a line break every time the first character changes.
There are a few ways we can do this, though the easiest involves preserving the range-based for loop and creating a new variable to store the last letter, so when the current first letter differs from the previous letter, we print a line break.
Additionally, create a boolean
to flag whether it is the first string to be printed.
Below is an implementation of this.
public static void printList(List<Miejsce> list) {
char lastLetter = '\0';
boolean firstString = true;
for (Miejsce miejsce : list) {
if (!firstString && miejsce.getNumerMiejsca().charAt(0) != lastLetter) {
System.out.println();
}
System.out.print(miejsce.getNumerMiejsca() " ");
lastLetter = miejsce.getNumerMiejsca().charAt(0);
firstString = false;
}
}
However, this does create trailing spaces ' '
at the end of each line. If this is a concern, we can ditch the range-based for loop and instead do something like this.
public static void printList(List<Miejsce> list) {
for (int i = 0; i < list.size(); i ) {
System.out.print(list.get(i).getNumerMiejsca());
if(i != list.size()-1 && list.get(i).getNumerMiejsca().charAt(0) != list.get(i 1).getNumerMiejsca().charAt(0)) {
System.out.print('\n');
} else {
System.out.print(' ');
}
}
}
Both of these implementations should be pretty intuitive and simple.
CodePudding user response:
An alternative way with streams:
public static void printList(List<Miejsce> list) {
list.stream()
.map(Miejsce::getNumerMiejsca)
.collect(Collectors.groupingBy(
num -> num.charAt(0),
Collectors.collectingAndThen(
Collectors.toList(),
li -> String.join(" ", li))))
.values()
.forEach(System.out::println);
}