Java工具--stream流

过滤(filter)

List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<String> StringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");

// 筛选出所有的偶数  >>>[2, 4, 6, 8, 10]
List<Integer> evenList = numberList.stream().filter(num -> num%2==0).collect(Collectors.toList());
// 筛选出所有非a开头的字符串  >>>[orange, banana, grape, kiwi]
List<String> strList = StringList.stream().filter(item -> !item.startsWith("a")).collect(Collectors.toList());

统计

求最大最小和均值

使用 mapToInt() 求整数列表中的最大值、最小值、总和、平均值。

List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
// 10
int max = numberList.stream().mapToInt(Integer::intValue).max().getAsInt();
// 1
int min = numberList.stream().mapToInt(Integer::intValue).min().getAsInt();
// 55
int min = numberList.stream().mapToInt(Integer::intValue).sum();
// 5.5
double avg = numberList.stream().mapToInt(Integer::intValue).average().getAsDouble();

// 计算双精度列表中所有数字的平均值
List<Double> doubleList = Arrays.asList(1.1, 2.2, 3.3, 4.2, 5.2, 6.1);
// 3.6833333333333336
double average = doubleList.stream().reduce(0.0, (a, b) -> a + b) / doubleList.size();
double average2 = doubleList.stream().mapToDouble(Double::doubleValue).average().getAsDouble();
//获取年龄最大的学生
Student ageMaxStudent = list.stream().max(Comparator.companing(Student::getAge)).get();

//获取年龄最小的学生
Student ageMinStudent  = list.stream().min(Comparator.companing(Student::getAge)).get();
List<User> userList = getUserList();

// 获取房间数最大的用户信息  >>>Optional[ApplicationTest.User(id=5, areaCode=210400, name=王五, roomNum=5, peopleNum=6)]
Optional<User> maxUserInfo = userList.stream().max(Comparator.comparingInt(User::getRoomNum));

// 获取房间数最小的用户信息  >>>Optional[ApplicationTest.User(id=1, areaCode=210300, name=熊大, roomNum=1, peopleNum=2)]
Optional<User> minUserInfo = userList.stream().min(Comparator.comparingInt(User::getRoomNum));

求和(sum)

List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Double> doubleList = Arrays.asList(1.1, 2.2, 3.3, 4.2, 5.2, 6.1);
List<Long> longNumberList = Arrays.asList(10L, 30L, 50L, 60L, 70L, 80L, 90L);

// 55
int m = numberList.stream().mapToInt(Integer::intValue).sum();
// 22.1
double n = doubleList.stream().mapToDouble(Double::doubleValue).sum();
// 390
long w = longNumberList.stream().mapToLong(Long::longValue).sum();
// 55
int sum1 = numberList.stream().reduce(0, (a, b) -> a + b);
int sum2 = numberList.stream().reduce(0, Integer::sum);

求数量(count)

// 统计长度大于5的字符串数量  >>>2
long count = StringList.stream()
        .filter(str -> str.length()>5)
        .count();

// 计算整数列表中所有偶数的和  >>>30
int sum = numberList.stream()
        .filter(num -> num%2==0)
        .mapToInt(Integer::intValue)
        .sum();

// 查找字符串列表中所有字符串的长度的总和  >>>31
int lengthSum = StringList.stream().mapToInt(String::length).reduce(0, Integer::sum);

遍历(map)

List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<String> StringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");

// 以整数列表作为输入,返回每个元素的平方的新列表  >>>[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
List<Integer> squareList = numberList.stream().map(num -> num*num).collect(Collectors.toList());
// 以字符串列表作为输入,返回每个字符串的长度的新列表  >>>[5, 6, 6, 5, 5, 4]
// map中的方法可以简化成 .map(String::length)
List<Integer> lenList = StringList.stream().map(item -> item.length()).collect(Collectors.toList());

规约(reduce)

List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

// 10
int maxNum = numberList.stream().reduce(Integer::max).get();
// 1
int minNum = numberList.stream().reduce(Integer::min).get();
// 55
int sumNum = numberList.stream().reduce(0, Integer::sum);
// 55
int sum = numberList.stream().reduce(0, (a, b) -> a + b);
// 3628800
int product = numberList.stream().reduce(1, (a, b) -> a * b);
List<Integer> numberList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<String> StringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");

// 在整数列表中找出最大元素  >>>10
int max = numberList.stream().reduce(0, (a, b) -> a>b? a : b);
// 查找字符串列表中最长的字符串  >>>Optional[banana]
String maxLengthStr = StringList.stream().reduce((s1, s2) -> s1.length() > s2.length()? s1 : s2).toString();
// 查找字符串列表中最短的字符串  >>>Optional[kiwi]
String minLengthStr = StringList.stream().reduce((s1, s2) -> s1.length() < s2.length()? s1 : s2).toString();

将列表中的所有字符串连接成一个字符串

// apple@orange@banana@grape@apple@kiwi@
String concat1 = StringList.stream().reduce("", (a, b) -> a + b + "@");
// apple@orange@banana@grape@apple@kiwi
String concat2 = StringList.stream().collect(Collectors.joining("@"));
// apple@orange@banana@grape@apple@kiwi
String concat3 = String.join("@", StringList);

排序(sorted)

List<String> StringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");

// 将每个字符串装换为大写,然后按字母顺序排序
// [APPLE, APPLE, BANANA, GRAPE, KIWI, ORANGE]
List<String> sortedUpperCase = StringList.stream()
        .map(String::toUpperCase)
        .sorted()
        .collect(Collectors.toList());
List<Integer> numberList = Arrays.asList(12, 2, 33, 24, 5, 61, 27, 8, 39, 10);

// 升序  >>>[2, 5, 8, 10, 12, 24, 27, 33, 39, 61]
List<Integer> sort1NumberList = numberList.stream().sorted().collect(Collectors.toList());
List<Integer> sort2NumberList = numberList.stream().sorted(Comparator.comparing(item->item)).collect(Collectors.toList());
// 降序   >>>[61, 39, 33, 27, 24, 12, 10, 8, 5, 2]
List<Integer> sortReverseNumberList = numberList.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

// 降序  >>>[61, 39, 33, 27, 24, 12, 10, 8, 5, 2]
List<Integer> numberList1 = Arrays.asList(12, 2, 33, 24, 5, 61, 27, 8, 39, 10);
numberList1.sort((objectA, objectB) -> objectB.compareTo(objectA));
// 升序  >>>[2, 5, 8, 10, 12, 24, 27, 33, 39, 61]
List<Integer> numberList2 = Arrays.asList(12, 2, 33, 24, 5, 61, 27, 8, 39, 10);
numberList2.sort((objectA, objectB) -> objectA.compareTo(objectB));

若需要排序的不是简单数字列表,是对象列表
List sortNumberList = numberList.stream().sorted(Comparator.comparing(item->item.getAge())).collect(Collectors.toList());
studentList.sort((objectA, objectB) -> objectB.getAge().compareTo(objectA.getAge()));

// User对象的四个属性,(id,areaCode,name,roomNum,peopleNum)
List<User> userList = getUserList();

// 筛选出人数为偶数的数据,并按人数降序排序。
List<User> abcComputers = userList.stream()
        .filter(item -> item.getPeopleNum()%2==0)
        .sorted(Comparator.comparing(User::getPeopleNum).reversed())
        .collect(Collectors.toList());

去重(distinct)

// 去重   >>>[apple, orange, banana, grape, kiwi]
List<String> unique = StringList.stream().distinct().collect(Collectors.toList());

findAny() 和 findFirst()

使用 findAny() 和 findFirst() 获取第一条数据。

List<String> stringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");

String str1 = stringList.stream().filter(item -> item.endsWith("e")).findAny().orElse(null);
String str2 = stringList.stream().filter(item -> item.endsWith("e")).findAny().orElse(null);

findFirst() 和 findAny() 都是获取列表中的第一条数据,但是findAny()操作,返回的元素是不确定的,对于同一个列表多次调用findAny()有可能会返回不同的值。使用findAny()是为了更高效的性能。如果是数据较少,串行地情况下,一般会返回第一个结果,如果是并行(parallelStream并行流)的情况,那就不能确保是第一个。

判断(anyMatch,allMatch,noneMatch)

  1. anyMatch(T -> boolean)
    使用 anyMatch(T -> boolean) 判断流中是否有一个元素匹配给定的 T -> boolean 条件。
  2. allMatch(T -> boolean)
    使用 allMatch(T -> boolean) 判断流中是否所有元素都匹配给定的 T -> boolean 条件。
  3. noneMatch(T -> boolean)
    使用 noneMatch(T -> boolean) 流中是否没有元素匹配给定的 T -> boolean 条件。
List<String> stringList = Arrays.asList("apple", "orange", "grape", "apple");
List<Integer> numberList = Arrays.asList(12, 2, 33, 24, 5, 61, 27, 8, 39, 10);

// 存在元素以a开头   >>>true
boolean anyStartsWithA = stringList.stream().anyMatch(item -> item.startsWith("a"));
// 所有元素以e结尾   >>>true
boolean allEndsWithB = stringList.stream().allMatch(item -> item.endsWith("e"));
// 没有元素以g开头   >>>false
boolean noneStartsWithG = stringList.stream().noneMatch(item -> item.startsWith("g"));
// 没有元素以k开头   >>>true
boolean noneStartsWithK = stringList.stream().noneMatch(item -> item.startsWith("k"));
// 所有元素都是偶数   >>>false
boolean allEven = numberList.stream().allMatch(item -> item%2==0);

分组

	@Test
    public void test011() {
        // User对象的四个属性,(id,areaCode,name,roomNum,peopleNum)
    	List<User> userList = getUserList();

        /**  返回一个Map,其中键是areaCode,值是具有该areaCode的用户列表
         * {
         *  210400=[User(id=5, areaCode=210400, name=王五, roomNum=5, peopleNum=6)],
         *  210300=[User(id=1, areaCode=210300, name=熊大, roomNum=1, peopleNum=2), User(id=2, areaCode=210300, name=赵二, roomNum=2, peopleNum=3)],
         *  210100=[User(id=3, areaCode=210100, name=张三, roomNum=3, peopleNum=4), User(id=4, areaCode=210100, name=李四, roomNum=4, peopleNum=5)]
         *  }
         */
        Map<String, List<User>> areaCodeAndUserMap = userList
                .stream().collect(Collectors.groupingBy(User::getAreaCode));

        /** 按areaCode分组,并收集组中roomNum最大的User对象
         * {
         * 210400=Optional[User(id=5, areaCode=210400, name=王五, roomNum=5, peopleNum=6)],
         * 210300=Optional[User(id=2, areaCode=210300, name=赵二, roomNum=2, peopleNum=3)],
         * 210100=Optional[User(id=4, areaCode=210100, name=李四, roomNum=4, peopleNum=5)]
         * }
         */
        Map<String, Optional<User>> areaCodeAndMaxRoomMap = userList.stream()
                .collect(Collectors.groupingBy(
                        User::getAreaCode,
                        Collectors.maxBy(Comparator.comparingInt(User::getRoomNum))
                ));


        // 按areaCode分组,并将组中的userID收集为List
        // {210400=[5], 210300=[1, 2], 210100=[3, 4]}
        Map<String, List<Long>> areaCodeAndUserIdMap = userList
                .stream().collect(Collectors.groupingBy(
                        User::getAreaCode,
                        Collectors.mapping(User::getId, Collectors.toList())
                ));


        // 按areaCode分组,并统计个数
        // {210400=1, 210300=2, 210100=2}
        Map<String, Long> areaCodeNumMap = userList
                .stream().collect(
                        Collectors.groupingBy(User::getAreaCode, Collectors.counting())
                );


        // 按areaCode分组,并统计组中的roomNum平均值
        // {210400=5.0, 210300=1.5, 210100=3.5}
        Map<String, Double> areaCodeAndRoomSumMap = userList
                .stream().collect(
                        Collectors.groupingBy(User::getAreaCode, Collectors.averagingInt(User::getRoomNum))
                );


        // 按areaCode分组,并统计组中的roomNum和
        // {210400=5, 210300=3, 210100=7}
        Map<String, Integer> areaCodeAndRoomNumMap = userList
                .stream().collect(
                        Collectors.groupingBy(User::getAreaCode, Collectors.summingInt(User::getRoomNum))
                );

        // 按areaCode分组,并统计组中的peopleNum和
        // {210400=6, 210300=5, 210100=9}
        Map<String, Integer> areaCodeAndPeopleNumMap = userList
                .stream().collect(
                        Collectors.groupingBy(User::getAreaCode, Collectors.summingInt(User::getPeopleNum))
                );

    }
List<String> StringList = Arrays.asList("apple", "orange", "banana", "grape", "apple", "kiwi");

// 按字符串长度分组
Map<Integer, List<String>> groups = new HashMap<>();
for (String item : StringList) {
    int length = item.length();
    if (!groups.containsKey(length)) {
        groups.put(length, new ArrayList<>());
    }
    groups.get(length).add(item);
}

// {4=[kiwi], 5=[apple, grape, apple], 6=[orange, banana]}
System.out.println(groups);

toList() toSet() toMap()

用toMap方法时,必须确保选择的key是唯一且非空的

@Test
public void test011() {
    // User对象的四个属性,(id,areaCode,name,roomNum,peopleNum)
    List<User> userList = getUserList();
    
    // [210300, 210300, 210100, 210100, 210400]
    List<String> list1 = userList.stream().map(User::getAreaCode).collect(Collectors.toList());
    // [210400, 210300, 210100]
    Set<String> set1 = userList.stream().map(User::getAreaCode).collect(Collectors.toSet());

    
    /**
     * {
     * 李四=User(id=4, areaCode=210100, name=李四, roomNum=4, peopleNum=5), 
     * 张三=User(id=3, areaCode=210100, name=张三, roomNum=3, peopleNum=4), 
     * 熊大=User(id=1, areaCode=210300, name=熊大, roomNum=1, peopleNum=2), 
     * 赵二=User(id=2, areaCode=210300, name=赵二, roomNum=2, peopleNum=3), 
     * 王五=User(id=5, areaCode=210400, name=王五, roomNum=5, peopleNum=6)
     * }
     */
    Map<String, User> map1 = userList
            .stream().collect(Collectors.toMap(User::getName, Function.identity()));

    /**
     * {
     * 1=User(id=1, areaCode=210300, name=熊大, roomNum=1, peopleNum=2), 
     * 2=User(id=2, areaCode=210300, name=赵二, roomNum=2, peopleNum=3), 
     * 3=User(id=3, areaCode=210100, name=张三, roomNum=3, peopleNum=4), 
     * 4=User(id=4, areaCode=210100, name=李四, roomNum=4, peopleNum=5), 
     * 5=User(id=5, areaCode=210400, name=王五, roomNum=5, peopleNum=6)
     * }
     */
    Map<Long, User> map2 = userList
            .stream().collect(Collectors.toMap(User::getId, Function.identity()));
    
    // {李四=5, 张三=4, 熊大=2, 赵二=3, 王五=6}
    Map<String, Integer> map3 = userList
            .stream().collect(Collectors.toMap(User::getName, User::getPeopleNum));

    // {1=熊大, 2=赵二, 3=张三, 4=李四, 5=王五}
    Map<String, String> map4 = userList
            .stream().collect(Collectors.toMap(
                    item -> String.valueOf(item.getId()),
                    User::getName
            ));

}

备注

public List<User> getUserList() {
    List<User> userList = new ArrayList<>();
    userList.add(new User(1L, "210300", "熊大",1, 2));
    userList.add(new User(2L, "210300", "赵二",2, 3));
    userList.add(new User(3L, "210100", "张三",3, 4));
    userList.add(new User(4L, "210100", "李四",4, 5));
    userList.add(new User(5L, "210400", "王五",5, 6));
    return userList;
}

@Data
@NoArgsConstructor
@AllArgsConstructor
class User{
    private Long id;
    private String areaCode;
    private String name;
    private Integer roomNum;
    private Integer peopleNum;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值