A demonstration example
1. The traversal
List<Integer> integerList = new ArrayList<>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
integerList.stream().forEach(integer -> {
System.out.println(integer); / / 1, 2, 3
});
Copy the code
2. To weight
List<Integer> integerList = new ArrayList<>();
integerList.add(1);
integerList.add(1);
integerList.add(3);
integerList = integerList.stream().distinct().collect(Collectors.toList());
integerList.stream().forEach(integer -> {
System.out.println(integer); / / 1 to 3
});
Copy the code
3. Get one of the parameters in the object as a new List
List<UserInfo> userInfos = new ArrayList<>();
userInfos.add(UserInfo.builder().uid("1").build());
userInfos.add(UserInfo.builder().uid("2").build());
userInfos.add(UserInfo.builder().uid("3").build());
List<String> uidList = userInfos.stream().map(UserInfo::getUid).collect(Collectors.toList());
uidList.stream().forEach(uid -> {
System.out.println(uid); / / 1, 2, 3
});
Copy the code
4. Obtain a parameter in the object as a new Map
List<UserInfo> userInfos = new ArrayList<>();
userInfos.add(UserInfo.builder().uid("1").build());
userInfos.add(UserInfo.builder().uid("2").build());
userInfos.add(UserInfo.builder().uid("3").build());
Map<String, String> uidMap = userInfos.stream().map(UserInfo::getUid).collect(Collectors.toMap(String::toString, String::toString));
uidMap.forEach((key, value) -> {
System.out.println(key + ":" + value);
});
/ / 1:1
/ / 2:2
/ / 3-3
Copy the code
5. The filter
List<UserInfo> userInfos = new ArrayList<>();
userInfos.add(UserInfo.builder().uid("1").build());
userInfos.add(UserInfo.builder().uid("2").build());
userInfos.add(UserInfo.builder().uid("3").build());
List<UserInfo> userInfoList = userInfos.stream().
// Filter
filter(userInfo -> userInfo.getUid().equals("1")).
// Object reorganization
map(userInfo -> UserInfo.builder().uid(userInfo.getUid()).build()).
// Collect results
collect(Collectors.toList());
/ / 1
Copy the code
6. The sorting
List<UserInfo> userInfos = new ArrayList<>();
userInfos.add(UserInfo.builder().uid("1").username("1").build());
userInfos.add(UserInfo.builder().uid("2").username("1").build());
userInfos.add(UserInfo.builder().uid("3").username("1").build());
userInfos.add(UserInfo.builder().uid("1").username("2").build());
userInfos.stream()
// Sort (the second sort can be set. ThenComparing ()) reversed
.sorted(Comparator.comparing(UserInfo::getUid).reversed())
.collect(Collectors.toList())
.forEach(userInfo -> {
System.out.println(userInfo.getUid()); / / 3,2,1,1
});
userInfos.stream()
// Sort: sort by uid first, then reverse, and then sort by username
.sorted(Comparator.comparing(UserInfo::getUid).reversed().thenComparing(UserInfo::getUsername))
.collect(Collectors.toList())
.forEach(userInfo -> {
System.out.println(userInfo.getUid()+"+"+userInfo.getUsername());
/ / 3 + 1
/ / 2 + 1
/ / 1 + 1
/ / 1 + 2
});
Copy the code
Group 7.
Collectors can be used as Collectors (Collectors. ToList () \ Collectors. ToSet ()). It can also be used as a data group, such as Collectors. GroupingBy ()
List<UserInfo> userInfos = new ArrayList<>();
userInfos.add(UserInfo.builder().uid("1").username("1").build());
userInfos.add(UserInfo.builder().uid("2").username("1").build());
userInfos.add(UserInfo.builder().uid("1").username("1").build());
userInfos.add(UserInfo.builder().uid("1").username("2").build());
// Single conditional grouping
Map<String, List<UserInfo>> collect = userInfos.stream().collect(Collectors.groupingBy(UserInfo::getUsername));
collect.forEach((key, value) -> {
System.out.print(key);
System.out.print("- >");
System.out.println(value.size());
});
// Multi-conditional grouping
Map<List<String>, List<UserInfo>> collect1 = userInfos.stream().collect(Collectors.groupingBy(v -> Arrays.asList(v.getUid(), v.getUsername()), Collectors.toList()));
collect1.forEach((key, value) -> {
System.out.print(key);
System.out.print("- >");
System.out.println(value.size());
});
Copy the code
8. Use two values in the object to form a Map
List<UserInfo> userInfos = new ArrayList<>();
userInfos.add(UserInfo.builder().uid("1").username("n1").build());
userInfos.add(UserInfo.builder().uid("2").username("n1").build());
userInfos.add(UserInfo.builder().uid("1").username("n1").build());
userInfos.add(UserInfo.builder().uid("1").username("n2").build());
Map<String, String> collect = userInfos.stream()
.collect(Collectors.toMap(UserInfo::getUid, UserInfo::getUsername));
// output Map as (1,1)
Copy the code
There’s a pit here
1. Repeating the Key
Solution one, cover
By default, this method raises IllegalStateException: Duplicate Key exception when keys are duplicated. Can be set to duplicate Key when overwriting.
Map<String, String> collect = userInfos.stream()
.collect(Collectors.toMap(UserInfo::getUid, UserInfo::getUsername, (oldValue, newValue) -> newValue));
/ / output
// 1 -> n2
// 2 -> n1
Copy the code
Solution two, splicing
Map<String, String> collect = userInfos.stream()
.collect(Collectors.toMap(UserInfo::getUid, UserInfo::getUsername, (oldValue, newValue) -> oldValue + "," + newValue));
collect.forEach((k, v) -> {
System.out.println(k + "- >" + v);
});
/ / output
// 1 -> n1,n1,n2
// 2 -> n1
Copy the code
2. The Value is empty
Solution 1
Map<String, Object> collect = userInfos.stream()
.collect(Collectors.toMap(UserInfo::getUid, v -> Optional.ofNullable(v.getUsername())));
/ / output
1 -> Optional.empty
2 -> Optional[n1]
Copy the code
Solution 2 (This method automatically overrides)
Map<String, Object> collect = userInfos.stream()
.collect(HashMap::new,
(n, v) -> n.put(v.getUid(), v.getUsername()), HashMap::putAll);
/ / output
//1 -> null
//2 -> n1
Copy the code
2. Method summary
1.1.forEach(v ->{ })
Traversal, the order is not necessarily (parallel stream processing, higher efficiency)
1.2.forEachOrdered(v ->{ })
Traversal, in strict element order (less efficient)
2.1.map()
You can think of it as a “handler” that can do something to an object in a list, return any type, and get a list of any type. For example, get the uid in an object as a list
List<UserInfo> userInfos = new ArrayList<>();
userInfos.add(UserInfo.builder().uid("1").build());
userInfos.add(UserInfo.builder().uid("2").build());
userInfos.add(UserInfo.builder().uid("3").build());
// Two ways of writing
List<String> uidList = userInfos.stream().map(UserInfo::getUid).collect(Collectors.toList());
List<String> uidList1 = userInfos.stream().map(userInfo -> {returnuserInfo.getUid(); }).collect(Collectors.toList()); uidList.stream().forEach(uid -> { System.out.println(uid);/ / 1, 2, 3
});
Copy the code
2.2.peek()
The function is similar to.map(), but does not change the object of the list. It is usually used as an intermediate operation or as a Lambda to view the properties of the current list. Such as:
List<UserInfo> userInfos = new ArrayList<>();
userInfos.add(UserInfo.builder().uid("1").username("1").build());
userInfos.add(UserInfo.builder().uid("2").username("1").build());
userInfos.add(UserInfo.builder().uid("1").username("1").build());
userInfos.add(UserInfo.builder().uid("1").username("2").build());
userInfos.stream().peek(System.out::println).forEach(userInfo -> {
System.out.println(userInfo.getUid());
});
// Output result:
UserInfo(uid=1, username=1)
1
UserInfo(uid=2, username=1)
2
UserInfo(uid=1, username=1)
1
UserInfo(uid=1, username=2)
1
Copy the code
As you can see, each parameter is executed before the method in forEach() is executed. Peek (). This allows you to both see the dynamics of each element in.peek() and do some object manipulation in.peek(). Note, however, that unlike.map(),.peek() is not the end of the chain call and cannot be used alone. It must be followed by collectors, traversers, etc. userInfos.stream().peek(System.out::println); There will be no output.
3.collect()
Collector, which can collect results as a List or Map, for example,.collect(Collectors. ToList ())
4.sorted()
Sorted (Comparator.comparing(UserInfo::getUid))
Sorted ((v1, v2) -> {return v1.getuid ().compareto (v2.getuid ()); })
The first method is recommended if you do not need to do complex processing.
5.filter()
.filter(userInfo -> userinfo.getuid ().equals(“1”));
6.limit()
Take a Long to get the first few items in the list. For example, obtain the first two items userinfos.stream ().limit(2).collect(Collectors. ToList ())
7.count()
Gets the size of the list
8.toArray()
Object[] objects = userinfos.stream ().toarray ();
9.max()\.min()
Get the maximum \ minimum according to the condition and accept the same argument as 3.sorted()
For example, get the object with the smallest UID
UserInfo userInfo = userInfos.stream().min(Comparator.comparing(UserInfo::getUid)).get();
10.reduce()
Computes according to the given algorithm and returns the result
For example, calculate a sum of 1,2,3,4.
List<Integer> integerList = new ArrayList<>();
integerList.add(1);
integerList.add(2);
integerList.add(3);
integerList.add(4);
// Two ways to write, two arguments
Integer reduce1 = integerList.stream().reduce((v1, v2) -> v1 + v2);
The first parameter is a default value, and the final result will be added to this value
Integer reduce2 = integerList.stream().reduce(1, (v1, v2) -> v1 + v2);
Integer reduce3 = integerList.stream().reduce(1, Integer::sum);
System.out.println(reduce1); / / 10
System.out.println(reduce2); / / 11
System.out.println(reduce3); / / 11
Copy the code
11.distinct()
Get rid of duplicate objects
userInfos.stream().distinct().forEach(userInfo -> {
System.out.println(userInfo.getUid() + "+" + userInfo.getUsername());
});
Copy the code
12..anyMatch()\.allMatch()\.noneMatch()
AnyMatch returns true if any of the criteria are successful
AllMatch says, check the elements in the condition, all of them are true, and return true
NoneMatch, as opposed to allMatch, evaluates the elements in the condition, all of which are not, and returns true
Such as,
List<Integer> strs = Arrays.asList(1.2.1.4.1);
boolean a = strs.stream().anyMatch(str -> str.equals(1));
boolean b = strs.stream().allMatch(str -> str.equals(2));
boolean c = strs.stream().noneMatch(str -> str.equals(3));
System.out.println(a);// true
System.out.println(b);// false
System.out.println(c);// true
Copy the code
13.findFirst()
Gets the first object in the current list, as in
UserInfo userInfo = userInfos.stream().findFirst().get();
Copy the code
14.Collectors
Collectors can be used as Collectors (Collectors. ToList () \ Collectors. ToSet ()). It can also be used as a data group, such as Collectors. GroupingBy ()
List<UserInfo> userInfos = new ArrayList<>();
userInfos.add(UserInfo.builder().uid("1").username("1").build());
userInfos.add(UserInfo.builder().uid("2").username("1").build());
userInfos.add(UserInfo.builder().uid("1").username("1").build());
userInfos.add(UserInfo.builder().uid("1").username("2").build());
Map<String, List<UserInfo>> collect = userInfos.stream().collect(Collectors.groupingBy(UserInfo::getUsername));
collect.forEach((key, value) -> {
System.out.print(key);
System.out.print("- >");
System.out.println(value.size());
});
Map<List<String>, List<UserInfo>> collect1 = userInfos.stream().collect(Collectors.groupingBy(v -> Arrays.asList(v.getUid(), v.getUsername()), Collectors.toList()));
collect1.forEach((key, value) -> {
System.out.print(key);
System.out.print("- >");
System.out.println(value.size());
});
Copy the code
Three, monomer operation
The object fetched by.findFirst() cannot be used directly, but requires singleton operations such as.get()\.orelse ().
1.1.get()
Gets the element
1.2.orElse()
Similar to.get(), but you can set a default value that is returned when the object is empty
Like a Stream of (” one “, “two”, “three”, “four”). The findFirst (). OrElse (” five “);
2.isPresent()
Returns a Boolean value to determine whether the object is null.