如何在Java中减去两个列表/数组的值?
问题描述:
我正在研究Java项目,但遇到了问题.我想在列表/数组c中减去两个列表或数组a和b,但是我不知道该怎么做.我希望"a [i] -b [i]"应该在下一个列表c中,对于5-2 = 3,其值应为c[i]
类似,任何建议和帮助将不胜感激.
I am working on a Java project and I am having a problem. I want to have the subtract of two lists or arrays a and b in list/array c but I don't know how to do that. I want "a[i] -b[i]" should be in next list c where the value should be c[i]
similarly for 5-2=3 any suggestion and help would be appreciated.
代码:
public static void länge() {
{
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(new File("C:\\Users/Voodoothechild/Desktop/Pidata/Anfang.txt")));
String line = null;
while ((line = br.readLine()) != null) {
{
BufferedReader bro = null;
try {
bro = new BufferedReader(new FileReader(new File("C:\\Users/Voodoothechild/Desktop/Pidata/Ende.txt")));
String lines = null;
while ((lines = br.readLine()) != null) {
String[] anfang = line.split("\n");
String[] ende = lines.split("\n");
List<Integer> an = new ArrayList<Integer>();
List<Integer> en = new ArrayList<Integer>();
for (int index = 0 ; index<ende.length ; index++) {
an.add(Integer.parseInt(anfang[index]));
en.add(Integer.parseInt(ende[index]));
Integer[] anf = new Integer[an.size()];
int[] result = new int[anf.length];
for (int i = 0; i < result.length; i++) {
result[i] = anf[i] - end[i];
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bro != null) {
try {
bro.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch(IOException e) {
e.printStackTrace();
}
}
}
}
}
答
使用Stream API可以轻松完成:
It can be done easily using Stream API:
int[] list1 = {4,2,1};
int[] list2 = {2,2,-1};
IntStream.range(0, list1.length)
.mapToObj(i -> list1[i] - list2[i])
.collect(Collectors.toList());
或者甚至更容易使用Javaslang:
or even easier using Javaslang:
Stream.range(0, list1.length)
map(i -> list1[i] - list2[i]);
或将两个列表压缩在一起:
or by zipping two lists together:
List.ofAll(list1)
.zip(List.ofAll(list2))
.map(t -> t._1 - t._2);