Search code examples
javajava-stream

Issue with sorting and creating map using java8


i have a code like these

@Data
public class person{
  String firstName;
  String lastName;
  int orderNum;
}

List<person> personList = new ArrayList<person>();

i am trying to sort object and trying get map based on order number.

i wrote a logic these this and didn't work for me

Map<String, String> xza = personList.stream()
  .sorted(Comparator.comparing(refDataDto::getOrderNum))
  .collect(Collectors.toList())
  .stream()
  .collect(Collectors.toMap(refDataDto::getFirstName, refDataDto::getastName));

Solution

  • You are sorting a list according to the order number, collecting it into a list, creating a stream from the list and then collecting the stream to an unsorted map. Maps don't, by default, preserve the order in which the key-value pairs are inserted.

    What you need is a LinkedHashMap, but since there is not a ready made collector helper for it, you have to set it up manually (and you don't need to collect the data to a list in between):

    Also, since you are working on streams containing Person objects, the lambdas need to refer to the Person class, not refDataDto.

    Map<String, String> xza = personList.stream()
        .sorted(Comparator.comparing(Person::getOrderNum))
        .collect(Collectors.toMap(
                Person::getFirstName,
                Person::getLastName,
                (v1, v2) -> {
                    throw new IllegalStateException("Key conflict");
                },
                LinkedHashMap::new));