1. list分组后统计

    List<UserInfo> userList = Lists.newArrayList();
         Map<String, Long> collect = userList.stream()
                 .collect(Collectors.groupingBy(UserInfo::getId, Collectors.counting()));
  2. 排序后取topN
List<InfoVo> collect = InfoVos.stream()
                .sorted(Comparator.comparing(InfoVo::getUserType).thenComparing(InfoVo::getItime))
                .limit(3)
                .collect(Collectors.toList());
  1. 如何获取一个连续数字组成的集合或者数组
@Test
public void test() {
    List<Integer> list = Stream.iterate(1, n -> n + 1).limit(20).collect(Collectors.toList());
    List<Integer> list1 = IntStream.rangeClosed(1, 20).boxed().collect(Collectors.toList());
    System.out.println(list);
    System.out.println(list1);
}

运行结果

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

个人评价:使用iterate的方式更优雅一些,可以自定义步长。但是哪个方式效率更好呢?

效率评测

@Test
public void test() {
    int maxNum = 1000000;
    long startTime = System.currentTimeMillis();
    List<Integer> list = Stream.iterate(1, n -> n + 1).limit(maxNum).collect(Collectors.toList());
    long endTime = System.currentTimeMillis();

    System.out.println(endTime - startTime);

    startTime = System.currentTimeMillis();
    List<Integer> list1 = IntStream.rangeClosed(1, maxNum).boxed().collect(Collectors.toList());
    endTime = System.currentTimeMillis();
    System.out.println(endTime - startTime);
}

执行结果

78
26

评价:效率还是rangeClosed更高效

  1. 如何把一个数组转换成集合
int[] array2;
array2 = new int[]{3, 6, 3, 3};

Set<Integer> set = Arrays.stream(array2).boxed().collect(Collectors.toSet());
  1. 集合转数组
Set<Integer> set = new HashSet<>();
int[] a1 = set.stream().mapToInt(Integer::intValue).toArray();
int[] a2 = set.stream().mapToInt(Integer::valueOf).toArray();

求平安
15 声望0 粉丝

家人平平安安。


引用和评论

0 条评论