问题:使用Java 8 进行排序和创建映射时出现问题。

huangapple go评论68阅读模式
英文:

Issue with sorting and creating map using java8

问题

I have a code like this:

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

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

I am trying to sort objects and create a map based on the order number.

I wrote the following logic, but it didn't work for me:

Map<String, String> xza = personList.stream()
  .sorted(Comparator.comparing(Person::getOrderNum))
  .collect(Collectors.toList())
  .stream()
  .collect(Collectors.toMap(Person::getFirstName, Person::getLastName));
英文:

i have a code like these

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

List&lt;person&gt; personList = new ArrayList&lt;person&gt;();

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&lt;String, String&gt; xza = personList.stream()
  .sorted(Comparator.comparing(refDataDto::getOrderNum))
  .collect(Collectors.toList())
  .stream()
  .collect(Collectors.toMap(refDataDto::getFirstName, refDataDto::getastName));

答案1

得分: 3

你正在根据订单号对列表进行排序,将其收集到一个列表中,然后从该列表创建一个流,最后将流收集到一个未排序的映射中。默认情况下,映射不会保留插入键值对的顺序。

你需要的是一个LinkedHashMap,但由于没有现成的集合助手可用,你需要手动设置它(而且不需要在中间将数据收集到列表中):

此外,由于你正在处理包含 Person 对象的流,Lambda 表达式需要引用 Person 类,而不是 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));
英文:

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&lt;String, String&gt; xza = personList.stream()
    .sorted(Comparator.comparing(Person::getOrderNum))
    .collect(Collectors.toMap(
            Person::getFirstName,
            Person::getLastName,
            (v1, v2) -&gt; {
                throw new IllegalStateException(&quot;Key conflict&quot;);
            },
            LinkedHashMap::new));

答案2

得分: 2

Collectors.toMap(key, value) 默认会创建一个 HashMap,它是无序的。 如果要按照插入顺序排序,你需要使用 LinkedHashMap

此外,.collect(Collectors.toList()).stream() 是没有用的。sorted 可以给你一个已排序的流,而且你正在将其转换为列表,然后再转回流,所以它是无用的。

因此,尝试使用具有4个参数的 Collectors.toMap 重载方法,而不是2个参数的:https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap-java.util.function.Function-java.util.function.Function-java.util.function.BinaryOperator-java.util.function.Supplier-

Map<String, String> xza = personList.stream()
  .sorted(Comparator.comparing(Person::getOrderNum))
  .collect(Collectors.toMap(
    Person::getFirstName,
    Person::getLastName,
    (u, v) -> {
      throw new IllegalStateException(String.format("Duplicate key %s", u));
    },
    LinkedHashMap::new));
英文:

Collectors.toMap(key,value), will by default create a HashMap, which is unordered. You have to use a LinkedHashMap to order it in the same order of elements that were inserted in.

Also, .collect(Collectors.toList()).stream() is not useful. sorted would have given you a sorted stream, and on top of it, you are converting it to a list and then back to stream, so it is useless.

So, try Collectors.toMap overloaded method with 4 parameters instead of 2: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#toMap-java.util.function.Function-java.util.function.Function-java.util.function.BinaryOperator-java.util.function.Supplier-

Map&lt;String, String&gt; xza = personList.stream()
  .sorted(Comparator.comparing(Person::getOrderNum))
  .collect(Collectors.toMap(
    Person::getFirstName,
    Person::getastName,
    (u, v) -&gt; {
      throw new IllegalStateException(String.format(&quot;Duplicate key %s&quot;, u));
    },
    LinkedHashMap::new));

huangapple
  • 本文由 发表于 2023年5月25日 18:39:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76331382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定