stream常用操作

a快乐码农發表於2024-12-02

Java Stream物件轉換為Map

方法1:透過收集器(Collector)使用toMap()方法

Map<KeyType, ValueType> map = stream.collect(Collectors.toMap(obj -> obj.getFieldKey(), obj -> obj.getFieldValue()));

方法2:結合Collectors的toMap()方法和Function.identity(),使用物件自身作為key

Map<Object, ObjectType> map = stream.collect(Collectors.toMap(ObjectType::getFieldKey, Function.identity()));

方法3:如果存在重複的key,可以使用BinaryOperator來指定如何處理衝突的值

Map<KeyType, ValueType> map = stream.collect(Collectors.toMap(ObjectType::getFieldKey, ObjectType::getFieldValue, (value1, value2) -> value1));

方法4:使用Collectors的toMap()方法和Collectors.groupingBy()方法結合,將stream按照某個屬性分組後轉換為Map

Map<GroupKeyType, Map<KeyType, ValueType>> map = stream.collect(Collectors.groupingBy(ObjectType::getGroupKey, Collectors.toMap(ObjectType::getFieldKey, ObjectType::getFieldValue)));

方法5:使用Collectors的toMap()方法和Collectors.groupingBy()方法結合,將stream按照某個屬性分組並彙總為List後轉換為Map

Map<GroupKeyType, List<ObjectType>> map = stream.collect(Collectors.groupingBy(ObjectType::getGroupKey, Collectors.toList()));

map 方法用於對映每個元素到對應的結果

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 獲取對應的平方數
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

filter 方法用於透過設定的條件過濾出元素

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 獲取空字串的數量
long count = strings.stream().filter(string -> string.isEmpty()).count();

limit 方法用於獲取指定數量的流

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

sorted 方法用於對流進行排序

Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);

parallelStream 是流並行處理程式的代替方法

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
// 獲取空字串的數量
long count = strings.parallelStream().filter(string -> string.isEmpty()).count();

Collectors 類實現了很多歸約操作,例如將流轉換成集合和聚合元素。Collectors 可用於返回列表或字串:

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
 
System.out.println("篩選列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合併字串: " + mergedString);

  

相關文章