Stream相关

使用groupingBymapping

//构建基本模型类Person
public static class Person {
    private String name;
    private String type;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public Person(String name, String type) {
        this.name = name;
        this.type = type;
    }
}

//使用
@Test
public void test24() {
    List personList = new ArrayList<>();
    personList.add(new Person("1", "8"));
    personList.add(new Person("2", "7"));
    personList.add(new Person("3", "6"));
    personList.add(new Person("2", "5"));
    personList.add(new Person("5", "4"));

    Map> map = personList
            .stream()
            .collect(Collectors.groupingBy(Person::getName,
                    Collectors.mapping(Person::getType, Collectors.toSet())));
    // toMap需要传进去一个BiFunction 用于发现key重复时采取的策略,是覆盖还是不覆盖
    Map map1 = personList
            .stream()
            .collect(Collectors.toMap(Person::getName,
                    t -> t.getType(),
                    (a, b) -> a));
    System.out.println(map);
    System.out.println(map1);
}

输出:
//map
{1=[8], 2=[5, 7], 3=[6], 5=[4]}
//map1
{1=8, 2=7, 3=6, 5=4}

使用Reduce

package reduce;

/**
 * @Description
 * @Authror taren
 * @DATE 2019/7/10 14:36
 */
public class Foo {
private String name;
private String type;
private Double typeValue;
private Integer count;

public Foo(String name, String type, Double typeValue, Integer count) {
    this.name = name;
    this.type = type;
    this.typeValue = typeValue;
    this.count = count;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public Double getTypeValue() {
    return typeValue;
}

public void setTypeValue(Double typeValue) {
    this.typeValue = typeValue;
}

public Integer getCount() {
    return count;
}

public void setCount(Integer count) {
    this.count = count;
}
}

@Test
public void test2() {
    List fooList = Lists.newArrayList(
            new Foo("A", "san", 1.0, 2),
            new Foo("A", "nas", 13.0, 1),
            new Foo("B", "san", 112.0, 3),
            new Foo("C", "san", 43.0, 5),
            new Foo("B", "nas", 77.0, 7),
            new Foo("D", "tan", 79.0, 9)
    );
    Integer e = fooList.stream().map(Foo::getCount).reduce(Integer::min).orElse(new Integer(2));
    System.out.println(e);
}
这是最简单的使用reduce了,有时间继续

你可能感兴趣的:(Stream相关)