首页 新闻 赞助 找找看

20200116

0
[待解决问题]

package com.pab.cloudpay.centrality.server;

import org.junit.Test;

import java.math.BigInteger;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import java.util.stream.Stream;

public class Main3 extends StreamData {

/**
 * 数组变成流:重载的方法,可以有始末
 * 注意这个方法的开环与闭环:stream(T[] array, int startInclusive, int endExclusive)
 */
private static Stream<Integer> arrStream = Arrays.stream(intArray, 1, 3);
private static Stream<String> strStream = strList.stream();
private static Stream<String> strStream02 = Stream.of("gently", "down", "the", "stream");
private static Stream<String> emptyStream = Stream.empty();

/**
 * 1)随机产生无限个echo,所以一定要limit截住,否则 outOfMemoryException
 * 2)只产生一个echo哦
 * 3)随机产生数字
 * 4)generate()方法一定是无限流
 */
private static Stream<String> generateStream = Stream.generate(() -> "echo");
private static Stream<String> ofEchoStream = Stream.of("echo");
private static Stream<Double> randomStream = Stream.generate(Math::random);
/**
 * 起始值为0,每次加1
 */
private static Stream<BigInteger> intStream02 = Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));

/**
 * 合并流
 */
private static Stream<String> combineStream = Stream.concat(strStream02,ofEchoStream);

/**
 * 并行流
 * isParallel():判断是否是并行流
 */
private static Stream<String> strStream03 = strList.parallelStream();
private static Stream<String> strStream04 = strList.stream().parallel();

/**
 * list 转 hashMap 类型
 * 注意map的泛型,以及toMap里面的参数值
 * list 转其他map类型待续
 */
@Test
public void toMap(){
    Map<String, String> collect = userList.stream().collect(Collectors.toMap(StreamData::getId, StreamData::getName));
    // 注意看 Function.identity() 源码:就是类似于 i -> i;如果流中 StreamData::getId 有一样的话,则 throw an IllegalStateException
    Map<String, StreamData> collect02 = userList.stream().collect(Collectors.toMap(StreamData::getId, Function.identity()));
    // 当有多个相同key值的时候,要保留哪个value值呢,就用下面那个方法(这里的策略是用新值)
    Map<String, StreamData> collect1 = userList.stream().collect(Collectors.toMap(StreamData::getId, Function.identity(), (existingValue, newValue) -> newValue));
    collect1.forEach((k,v) -> System.out.println(k + "," + v));
    // 如果要 value 值是个集合,看 groupingBy() 方法
}

/**
 * 流变数组
 */
@Test
public void streamToArray(){
    String[] strArr = strStream02.toArray(String[]::new);
}

/**
 * 1)map 方法里面的那个参数一定是一个lambda表达式  a.toUpperCase() ,如果里面  a.toUpperCase() ,则报错
 * 2)map 方法返回的一样是那个stream流,所以可以继续调用 方法,达到链式反应方法
 * 3)注意尽量用方法引用:map(String::toUpperCase);而不是:map(a -> a.toUpperCase())
 */
@Test
public void mapFlatMapMethod() {
    String str = strList.stream().map(String::toUpperCase).collect(Collectors.joining(","));
    List<Integer> list = intList02.stream().map(cost -> cost + 50).map(cost -> cost * 2).collect(Collectors.toList());
    List<Stream<Integer>> collect1 = StreamData.flatMapList.stream().map(Collection::stream).collect(Collectors.toList());
    /*
    输出:[1, 11, 2, 22, 3, 33, 4, 44, 5, 55]
    flatMap(i -> i.stream()) 可以变为  Collection::stream
    注意:这个 StreamData.flatMapList  里面的类型是个集合数组啊,所以才可以用stream方法嘛
     */
    List<Integer> collect = StreamData.flatMapList.stream().flatMap(Collection::stream).collect(Collectors.toList());
    // 输出:[2, 22, 4, 44, 6, 66, 8, 88, 10, 110]
    List<Integer> collect02 = StreamData.flatMapList.stream().flatMap(i -> i.stream().map(j -> j * 2)).collect(Collectors.toList());
}

/**
 * 集合遍历
 * 箭头左边表示参数
 * 箭头右边一定要是表达式,当里面有多个等式时,一定要用大括号哦
 */
@Test
public void iterator() {
    strList.forEach(a -> a += "eeee");
    strList.forEach(a -> {
        a += "ddd";
        System.out.println(a += "ddd");
        System.out.println(a + "ccc");
    });
}


/**
 * 对元素进行处理之后,再进行统计;Collectors的方法不能对元素进行处理,要不就要for循环进行遍历
 * Stream<E> 流对象 有 mapToInt、mapToLong、mapToDouble 方法,分别返回 IntStream、LongStream、DoubleStream 对象
 * IntSummaryStatistics 一共有:getMax()、getMin()、getAverage()、getCount()、getSum() 五种方法
 */
@Test
public void primitiveTypeStreams() {
    IntStream stream = IntStream.of(1, 1, 2, 3, 5);
    IntSummaryStatistics iss = intList.stream().mapToInt(i -> i + 1).summaryStatistics();
}

/**
 * 去重
 * peek():就把流中的分别遍历打印吧,感觉用处不大
 */
@Test
public void distinctPeek() {
    List<Integer> collect = intList.stream().distinct().peek(System.out::print).collect(Collectors.toList());
    // 有序排列:[4, 5, 6, 1, 2, 3, 7, 8, 9, 10]
    List<Integer> list = intList.stream().distinct().collect(Collectors.toList());
    // 无序排列:[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    Set<Integer> set = intList.stream().collect(Collectors.toSet());
}

/**
 * 双冒号:对参数不能有修改
 */
@Test
public void doubleColon() {
    // 变大写字母
    String str = strList.stream().map(String::toUpperCase).collect(Collectors.joining());
    //求和
    int sum = intList.stream().mapToInt(Integer::intValue).sum();

}

/**
 * 过滤
 */
@Test
public void filterFindFirstAnyAllMatch() {
    // 过滤出长度大于2的字符串:找到第一个
    Optional<String> first = strList.stream().filter(i -> i.length() > 2).findFirst();
    /*
    1)过滤出偶数列表
    2)findAny(): If you are OK with any match, not just the first one, use the findAny method.
    This is effective when you parallelize the stream, since the stream can report any match that it finds
    instead of being constrained to the first one.
     */
    Optional<Integer> any = intList.stream().parallel().filter(i -> i % 2 == 0).findAny();
    // match:注意可以用并行流
    boolean flag = strStream.parallel().allMatch(i -> i.length() > 3);
    boolean flag02 = strList.stream().parallel().anyMatch(i -> i.length() > 3);
    boolean flag03 = strList.parallelStream().noneMatch(i -> i.length() > 3);
}

/**
 * 对里面的值处理再相加
 */
@Test
public void mapReduce() {
    // 为每个订单加上12%的税;因为只有一个参数,所以cost也可以不用括号;sum是自定义的一个变量
    double bill = intList02.stream().map(cost -> cost * 1.12).reduce((sum, cost) -> sum + cost).get();
    System.out.println("Total : " + bill);
}

@Test
public void test01() {
    //转成其它数据结构比如set
    Set<Integer> integersSet = intList.stream().collect(Collectors.toSet());
    //复合操作
    List<Integer> list = intList.stream().filter(i -> i % 2 == 0).map(i -> i * i).distinct().collect(Collectors.toList());
}

/**
 * 排序并取出前n个元素
 * sorted(): It sorts the elements of stream using natural ordering. The element class must implement Comparable interface.
 * sorted(Comparator<? super T> comparator): Here we create an instance of Comparator using lambda expression. We can sort the stream elements in ascending and descending order.
 * To reverse the natural ordering Comparator provides reverseOrder() method. We use it as follows:list.stream().sorted(Comparator.reverseOrder())
 */
@Test
public void sortLimitSkip() {
    // 只获取前面多少位啊
    Stream<Double> limit = randomStream.limit(6);
    // skip():跳过前面多少位数字
    Stream<Integer> skip = intList.stream().limit(5).skip(2);
    // 取出前五个数据 [4, 5, 6, 1, 2]
    List<Integer> limitInteger = intList.stream().limit(5).collect(Collectors.toList());
    //排序并且提取出前5个元素 [1,2,3,4,5]
    List<Integer> sortIntegers = intList.stream().sorted().limit(5).collect(Collectors.toList());
    List<Integer> collect1 = intList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());
    /*
    根据长度排行,正序或者倒序:
    1)要用 Comparator.comparing(String::length) ,不要用 Comparator.comparing(obj -> obj.length())
    2)核心,里面放一个 Comparator 对象
     */
    List<String> collect = strList.stream().sorted(Comparator.comparing(String::length)).collect(Collectors.toList());
    List<String> collect03 = strList.stream().sorted(Comparator.comparing(String::length,Comparator.reverseOrder())).collect(Collectors.toList());
    List<String> collect04 = strList.stream().sorted(Comparator.comparing(String::length).reversed()).collect(Collectors.toList());
    // 根据用户名字字母顺序排名,反序(终极版本)
    List<StreamData> collect2 = userList.stream().sorted(Comparator.comparing(StreamData::getAge).thenComparing(StreamData::getName).thenComparing(StreamData::getPwd)).collect(Collectors.toList());
    // 得到年龄最大的 StreamData:核心也是放一个比较器
    Optional<StreamData> max = userList.stream().max(Comparator.comparing(StreamData::getAge));

}

/**
 * 分组:groupingBy
 */
@Test
public void groupingPartitioningBy() {
    Map<String, List<StreamData>> collect = userList.stream().collect(Collectors.groupingBy(StreamData::getId));
    // 根据奇偶性分组:{false=[5, 1, 3, 7, 9], true=[4, 6, 2, 8, 8, 10]}
    Map<Boolean, List<Integer>> listMap = intList.stream().collect(Collectors.groupingBy(i -> i % 2 == 0));
    /*
    When the classifier function is a predicate function (that is, a function returning a boolean value), the stream elements are partitioned into two lists:
    those where the function returns true and the complement. In this case, it is more efficient to use partitioningBy instead of groupingBy.
     */
    Map<Boolean, List<Integer>> collect1 = intList.stream().collect(Collectors.partitioningBy(i -> i % 2 == 0));
    collect.forEach((k,v) -> System.out.println(k + "," + v));
}

}

@Data
@AllArgsConstructor
@NoArgsConstructor
public class StreamData {

public static List<String> strList = Arrays.asList("aaaaa", "c", "bbb", "dd", "cc", "eeeeee", "fff", "zzz");
public static List<Integer> intList = Arrays.asList(4, 5, 6,1, 2, 3,7, 8,8,9,10);
public static List<Integer> intList02 = Arrays.asList(100, 200, 300, 400, 500);
public static Integer[] intArray = {4, 5, 6,1, 2, 3,7, 8,8,9,10};

public String id;
public String name;
public String pwd;
public Integer age;

public static List<StreamData> userList = new ArrayList<StreamData>(){
    {
        this.add(new StreamData("111", "guo", "111a", 11));
        this.add(new StreamData("222", "xiao", "222b", 22));
        this.add(new StreamData("333", "feng", "333c",23));
        this.add(new StreamData("444", "sadfaf", "444d", 22));
        this.add(new StreamData("444", "hasdghdsg", "444d", 22));
    }
};

public static List<List<Integer>> flatMapList = new ArrayList<List<Integer>>(){
    {
        this.add(Arrays.asList(1,11));
        this.add(Arrays.asList(2,22));
        this.add(Arrays.asList(3,33));
        this.add(Arrays.asList(4,44));
        this.add(Arrays.asList(5,55));
    }
};

}

天马行空郭的主页 天马行空郭 | 菜鸟二级 | 园豆:204
提问于:2020-01-16 16:34
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册