Lambda and Stream Practical Example Collection

Function < T, R > - Take T as input and return R as output
Predicate - Take T as input and return Boolean value as output
Consumer - Take T as input, perform certain operations and return nothing.
Supplier - No input, return T
IntConsumer - Take two T as input and return one T as output, which is useful for the "reduce" operation.

The most common way to get streams may come from collections: Stream stream = collection. stream ();
It's a new feature introduced in Java 8. It's an enhancement of Collection object functionality, which is about algorithms and computation, more like an advanced version of Iterator.

What can be used for: Convenient and efficient aggregation operations on collection objects, or mass data operations?

In the past, Iterator was used to traverse collections for aggregation operations, and the code was cumbersome. For filtering and computing intermediate results, additional space was needed to store Java Stream API to solve the above problems. Traversal logic can be reduced to one line, making the code more concise and readable. Java Stream provides both serial and parallel modes for aggregation operation, which can make full use of the advantages of multi-core processors, and make it easier to write high-performance concurrent programs without error.

Do the same thing for lists, similar to traversing lists, with a for loop

if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(entity -> {
                String jsonString = JSONObject.toJSONString(entity, SerializerFeature.WriteMapNullValue);
                Map dataMap = JSONObject.parseObject(jsonString);
            map.put(SysConstants.HttpConstants.COUNT, list.size());
            map.put("list", dataList);

Lambda has no way of breaking the loop or returning values from lambda that contain the results of this method.

final String secret ="foo";
boolean containsSecret(Iterable <String> values){
    values.forEach(s  - > {
            ??? //You want to end the loop and return true, but you can't

List sort of a string, ignoring case.

//List sort of a string, ignoring case.
List<String> list = Arrays.asList("a","e","c");
list.sort((s1,s2) -> s1.compareToIgnoreCase(s2));

Default constructor for new generated objects

//Default constructor for new generated objects
Supplier<Apple> s1 = Apple::new;
Apple apple = s1.get();
 Supplier<Apple> c1 = () -> new Apple();
Function<Integer,Apple> c2 = Apple::new;
Apple apple1 = c2.apply(1);
Function<Integer, Apple> c2 = (weight) -> new Apple(weight);

Print shopping list

    public void printShoppingList(){

Statistical Shopping List Total Number and Total Price

        long itemNum =;
        System.out.println("Sum of items in the shopping list: " + itemNum);
        long totalPrice =;
        /* long totalPrice =; */
        System.out.println("Total price: " + totalPrice);

Filtration of goods with a price less than 1000 -> p.getPrice() >= 1000L).forEach(System.out::println);

Price order

        /*Ascending order*/;

All commodity prices minus 100 - Map -> new Item(p.getItemName(),p.getPrice()-100)).forEach(System.out::println);
        /*Rearrange and find that the price is - 100 already.*/;

The lowest price (the cheapest luxury goods) of the goods with the amount exceeding 1000 yuan after taking out the above discount.

      Item cheapestluxury =
              .map(p -> new Item(p.getItemName(), p.getPrice() - 100))
              .filter(p -> p.getPrice() > 1000)
              .reduce((a, b) -> a.getPrice() < b.getPrice() ? a : b)

Find the number of strings less than 5 in a set. In filter there are filter conditions, true stays, and false puts forward
1.filter operation. Even if the elements satisfying the conditions in the original stream constitute a new stream

List<String> list = Arrays.asList("java", "scala", "python", "shell", "ruby");
        int num = 0;
        for(String lan: list) {
            if(lan.length() < 5) {
long num = list.parallelStream().filter(x -> x.length() < 5).count(); operation. map is one of the most commonly used operations, traversing the elements of the original stream and transforming it into a new stream:
Turn to capitalization.

List<String> list = Arrays.asList(new String[]{"a", "b", "c"});
//Below Collectors. toList (), the string will be accumulated into list. stream (). map (String:: to UpperCase). collect (Collectors. toList (). forEach (x - > System. out. print (x +");

3.distinct operation. Distinct is also one of the commonly used operations.
Find repetitive elements

Stream<String> distinctStream = Stream.of("bj","shanghai","tianjin","bj","shanghai").distinct();
Stream<String> sortedStream = distinctStream.sorted(Comparator.comparing(String::length));
sortedStream.forEach(x -> System.out.print(x + " "));

4. Sort operation.

Stream<Integer> sortedReverseStreamV2 = Stream.of(1,3,7,4,5,8,6,2).sorted((Integer o1, Integer o2) -> o2 - o1);
sortedReverseStreamV2.collect(Collectors.toList()).forEach(x -> System.out.print(x + " "));

1.reduction is a terminal operation that takes the result out of the stream, so the stream after reduction can no longer be used. It mainly includes the following operations: findFirst()/findAny()/allMatch/anyMatch()/noneMatch, and so on.

collect() method can deal with various elements in stream, and get the value of elements in stream. And the Collectors interface provides a convenient factory method for creating Collector objects.

        //Transfer to List < String > List < Integer >
        List<String> list1 =Stream.of("1", "3", "2").collect(Collectors.toList());
        List<Integer> list2 =  Stream.of(1,2,3).collect(Collectors.toList());
        //Building Set s
        Set<String> s1 = Stream.of("1","2","3").collect(Collectors.toSet());
        s1.forEach(p -> System.out.println(p + " "));
        //Construct streams as strings separated by commas
        String resultStr = Stream.of("hello", "world", "hello", "java").collect(Collectors.joining(","));

Tags: Java Lambda less Scala

Posted on Fri, 09 Aug 2019 05:29:03 -0700 by msielski