With the new features of java8, you can use simple and efficient code to achieve some data processing. \
Define 1 Apple object:
public class Apple { private Integer id; private String name; private BigDecimal money; private Integer num; public Apple(Integer id, String name, BigDecimal money, Integer num) { this.id = id; this.name = name; this.money = money; this.num = num; }}Copy the code
Add some test data:
List<Apple> appleList = new ArrayList<>();// Store the apple object collection
Apple apple1 = new Apple(1."Apple 1".new BigDecimal("3.25"),10);
Apple apple12 = new Apple(1."Apple 2".new BigDecimal("1.35"),20);
Apple apple2 = new Apple(2."Banana".new BigDecimal("2.89"),30);
Apple apple3 = new Apple(3."Litchi".new BigDecimal("9.99"),40);
appleList.add(apple1);
appleList.add(apple12);
appleList.add(apple2);
appleList.add(apple3);
Copy the code
1, grouping
Group object elements in a List by an attribute, for example, by id, and group them together with the same ID:
//List is grouped by ID Map
>
,list
Map<Integer, List<Apple>> groupBy = appleList.stream().collect(Collectors.groupingBy(Apple::getId));
System.err.println("groupBy:"+groupBy);
{1=[Apple{id=1, name=Apple '1', money=3.25, num=10}, Apple{id=1, name='apple 2', money=1.35, num=20}].2=[Apple{id=2, name='banana', money=2.89, num=30}].3=[Apple{id=3, name='lychee', money=9.99, num=40}}]Copy the code
2. Convert List to Map
Id = key and apple = value
/** * List -> Map * toMap Duplicate key.... * Apple1 and apple12 both have ids of 1. * Use (k1,k2)->k1. If there are duplicate keys, keep key1 and discard key2 */
Map<Integer, Apple> appleMap = appleList.stream().collect(Collectors.toMap(Apple::getId, a -> a,(k1,k2)->k1));
Copy the code
Print appleMap
{1=Apple{id=1, name=Apple '1', money=3.25, num=10}, 2=Apple{id=2, name='banana', money=2.89, num=30}, 3=Apple{id=3, name='lychee', money=9.99, num=40}}
Copy the code
3. Filter
Filter out qualifying elements from the collection:
// Filter out the data that meets the criteria
List<Apple> filterList = appleList.stream().filter(a -> a.getName().equals("Banana")).collect(Collectors.toList());
System.err.println("filterList:"+filterList);
[Apple{id=2, name='banana', money=2.89, num=30}]
Copy the code
4, sum
Sum the data in the collection according to an attribute:
// Calculate the total amount
BigDecimal totalMoney = appleList.stream().map(Apple::getMoney).reduce(BigDecimal.ZERO, BigDecimal::add);
System.err.println("totalMoney:"+totalMoney); / / totalMoney: 17.48
Copy the code
5. Find the maximum and minimum values in the stream
MaxBy and Collectors. MinBy to calculate the maximum or minimum value in the flow. Search Java bosom friend public account, reply “backend interview”, send you a Java interview questions treasure book
Optional<Dish> maxDish = Dish.menu.stream().
collect(Collectors.maxBy(Comparator.comparing(Dish::getCalories)));
maxDish.ifPresent(System.out::println);
Optional<Dish> minDish = Dish.menu.stream().
collect(Collectors.minBy(Comparator.comparing(Dish::getCalories)));
minDish.ifPresent(System.out::println);
Copy the code
6, to heavy
import static java.util.Comparator.comparingLong;
import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.toCollection;
// Remove weight by id
List<Person> unique = appleList.stream().collect(
collectingAndThen(
toCollection(() -> new TreeSet<>(comparingLong(Apple::getId))), ArrayList::new));Copy the code
The following table shows static factory methods for Collectors.
The factory method | The return type | role |
---|---|---|
toList | List<T> |
Collect all the items in the stream into a List |
toSet | Set<T> |
Collect all items in the stream into a Set and remove duplicates |
toCollection | Collection<T> |
Collects all items in the flow into a collection created by the given providermenuStream.collect(toCollection(), ArrayList::new) |
counting | Long | Count the number of elements in the stream |
sumInt | Integer | Summation of an integer property of an item in the stream |
averagingInt | Double | Calculates the average value of the item Integer attribute in the stream |
summarizingInt | IntSummaryStatistics | Collect statistics on the Integer attributes of items in the stream, such as maximum, minimum, sum, and average |
joining | String | Concatenate the string generated by calling the toString method for each item in the streamcollect(joining(", ")) |
maxBy | Optional<T> |
An Optional that wraps the largest element in the stream selected by the given comparator, or option.empty () if the stream is empty |
minBy | Optional<T> |
An Optional that wraps the smallest element in the stream selected by the given comparator, or option.empty () if the stream is empty |
reducing | The type produced by the reduction operation | Starting with an initial value that acts as an accumulator, the stream is reduced to a single value by combining elements in the stream one by one with a BinaryOperatorReduce (0, Dish::getCalories, Integer::sum); |
collectingAndThen | Converts the type returned by the function | Wrap another collector and apply conversion functions to its resultsint howManyDishes = menuStream.collect(collectingAndThen(toList(), List::size)) |
groupingBy | Map<K, List<T>> |
Group the items in the stream based on the value of one of their attributes and use the attribute value as the key of the resulting Map |
partitioningBy | Map<Boolean,List<T>> |
Items are partitioned based on the result of applying predicates to each item in the flow |
END
Source: suo. Im / 5 wpn61