search

Home  >  Q&A  >  body text

java - Stream.map()方法是保持原有顺序么?还是会重新排序呢?

PHP中文网PHP中文网2853 days ago1433

reply all(3)I'll reply

  • PHPz

    PHPz2017-04-18 10:12:56

    Hello, in the case of non-concurrent streams, the processing order of the map method of the stream depends on the order in which the stream currently processes the upstream collection. The order of the ArrayList defaults to the natural order (insertion order), so the ArrayList collection is converted to the map method of the stream. Ability to process collection elements in natural order.

    // 输出c b a
    List<String> a = new LinkedList<String>();
    a.add("c");
    a.add("b");
    a.add("a");
    a.stream().map(x -> {
      System.out.println(x);
      return x;
    }).count();
    
    Map<String,String> m = new HashMap<String,String>();
    m.put("4","D");
    m.put("2","B");
    m.put("1","A");
    m.put("3","C");
    // m.values() 默认顺序为A B C D
    // 因此stream map的处理顺序也是 A B C D
    m.values().stream().map(x -> {
                        System.out.println(x);
                        return x;
                    }).count();

    reply
    0
  • ringa_lee

    ringa_lee2017-04-18 10:12:56

    map Mapping, this has nothing to do with sorting.

    List<String> list = new ArrayList<>();
    list.add("A");
    list.add("B");
    
    list.stream().map((Function<String, Object>) s -> s + "1").forEach(System.out::println);
    // output:
    // A1
    // B1

    reply
    0
  • PHP中文网

    PHP中文网2017-04-18 10:12:56

    parallelStream does not guarantee the order, streamp guarantees the order

    reply
    0
  • Cancelreply