Skip to content

Instantly share code, notes, and snippets.

@naffan2014
Last active June 20, 2019 09:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naffan2014/3434bdeddca80a4fecb12a9aa3d2e109 to your computer and use it in GitHub Desktop.
Save naffan2014/3434bdeddca80a4fecb12a9aa3d2e109 to your computer and use it in GitHub Desktop.
增加说明文字

先来个demo

package myStream;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;


public class myStream {


    public static void main(String[] args) {

        List<Person> list = new ArrayList<Person>();
        list.add(new Person(1, "haha"));
        list.add(new Person(2, "rere"));
        list.add(new Person(3, "fefe"));

        //Map<Integer, String> mapp = list.stream().collect(Collectors.toMap(Person::getId,p->p.getName()+"abc",(x,y)->(x.equals("hahaabc")?x:y)));
        Map<Integer,Person> mapp  = list.stream().collect(Collectors.toMap(k->k.getId()+1,Function.identity()));

        System.out.println(mapp);

        System.out.println(mapp.get(2).getName());

        Map<Integer, String> map = list.stream().collect(Collectors.toMap(Person::getId, Person::getName));

        System.out.println(map);

    }

}


class Person {

    private Integer id;
    private String name;

    public Person(Integer id, String name) {
        this.id = id;
        this.name = name;
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

1.首先定义一个Person类

2.构造个List,存储Person实例

3.通过toMap方法将map的value增加”abc“标识,如果key重复就用第一个。

4.通过toMap方法将map的key都增加1.

通过例子来讲下tomap是怎么用的

1.首先看tomap的定义

public static <T, K, U>
    Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper,
                                    Function<? super T, ? extends U> valueMapper) {
        return toMap(keyMapper, valueMapper, throwingMerger(), HashMap::new);
    }

toMap的参数一共三个,第一个是keyMapper,是说明key怎么存储 第二个valueMapper说明value怎么存储。第三个是为了如果key有重复我们应该以哪个为准。

2.toMap的返回类型时 <T,?,Map<k.U>>。返回给collect。我们看下collect的定义

 <R, A> R collect(Collector<? super T, A, R> collector);

3.第三个参数R也就是collect要返回的类型。剩下的T和A分别定的上面的T和? 4.接下来我们就能够确定了Map的类型其实就是前面返回的R。而R是我们在toMap中已经规定好的类型。也就是<Integer,String>

当参数为Functin.identity()时会发生什么

static <T> Function<T, T> identity() {
        return t -> t;
    }
  1. 我们看到toMap中的前两参数都是Function。所以我们可以用函数式编程的思想,将Functin.identity()理解为传入什么值就输出什么值,也就是说什么都不变。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment