《Java核心技术I》并行数组算法

并行数组算法

Arrays类提供了大量并行化操作。

Arrays.parallelSort方法可以对一个基本类型值或对象的数组排序。

java 复制代码
package arrays;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;

public class ParallelSortTest {

    public static void main(String[] args) throws IOException {
        var contents = new String(
                Files.readAllBytes(Path.of("D:\\ChromeCoreDownloads\\eclipse-jee-2024-09-R-win32-x86_64\\eclipse\\eclipse-workspace\\JavaCore1\\src\\arrays\\alice.txt")),StandardCharsets.UTF_8);
//        System.out.println(contents);
        String[] words = contents.split("[\\P{L}]+");
        System.out.println(Arrays.toString(words));
        Arrays.parallelSort(words, Comparator.comparing(String::length));
        System.out.println(Arrays.toString(words));
    }

}

三种:

  • 默认排序:Arrays.parallelSort(words)
  • 提供比较器排序:Arrays.parallelSort(words, Comparator.comparing(String::length));
  • 只排序提供的范围:values.parallelSort(values.length/2,values.length);

parallelSetAll方法会用由一个函数计算得到的值填充一个数组。

java 复制代码
package arrays;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Comparator;

public class ParallelSetAllTest {

    public static void main(String[] args) throws IOException {
        int[] values = new int[20];
        Arrays.parallelSetAll(values, i->i+1);
        System.out.println(Arrays.toString(values));
    }

}
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]

最后一个parallelPrefix方法,用一个给定结合操作的相应前缀的累加结果替换各个数组元素。

java 复制代码
package arrays;

import java.util.Arrays;

public class ParallelPrefixTest {

    public static void main(String[] args) {
        int[] values = new int[] {1,2,3,4,5,6,7,8,9}; 
        Arrays.parallelPrefix(values, (x,y)->x+y);
        System.out.println(Arrays.toString(values));
    }

}
//[1, 3, 6, 10, 15, 21, 28, 36, 45]
相关推荐
Hardess-god1 分钟前
Spyder、PyCharm、VS Code 和 Jupyter Notebook 对比分析
ide·python·jupyter·pycharm
落笔映浮华丶3 分钟前
C++(进阶) 第11智能指针
开发语言·c++
ephemerals__5 分钟前
【c++11】c++11新特性(上)(列表初始化、右值引用和移动语义、类的新默认成员函数、lambda表达式)
开发语言·c++
froginwe117 分钟前
Scala Iterator(迭代器)
开发语言
雪夜行人16 分钟前
openpyxl合并连续相同元素的单元格
开发语言·python
weixin_4450547217 分钟前
力扣刷题-热题100题-第34题(c++、python)
c++·python·leetcode
姜行运18 分钟前
C++【string类】(一)
android·开发语言·c++
用户277844910499319 分钟前
Python使用OWASP ZAP进行Web应用安全测试
python·安全
烁34720 分钟前
每日一题(小白)暴力娱乐篇23
java·开发语言·算法·娱乐
学长论文辅导24 分钟前
基于Python的新能源汽车销量分析与预测(大数据毕设-Python/决策树)
大数据·python·决策树·毕业设计·回归算法