[英]Adding up values from a column that have the same value in another column
我正在嘗試添加列表中第 3 列中與第 2 列中具有相同值的值。例如,[2, 20003, 4] [2, 20003, 7] 將返回 [2,20003,11] ,因為他們在中間列共享 20003。
public static void main(String[] args) throws IOException
{
CSVReader reader = new CSVReader(new FileReader("file"), ',', '"', 1);
List<String[]> allRows = reader.readAll();
for(String[] row : allRows)
{
System.out.println(Arrays.toString(row));
}
}
示例輸出(獲取 3 列中的輸出) [1, 10002, 4] [1, 10004, 6] [1, 10008, 2] [1, 10010, 3] [1, 10010, 3] [2, 10007, 10 ] [2, 20003, 4] [2, 20003, 7] [2, 30019, 1] [2, 30020, 9]
這將用總和替換第三個元素,如果相同的第一個和第二個元素出現多次,則創建重復項:
Map<String, Integer> map
= allRows.stream()
.collect(Collectors.groupingBy(a -> a[1],
Collectors.summingInt(a -> Integer.valueOf(a[2]))));
List<String[]> out
= allRows.stream()
.map(a -> new String[]{a[0], a[1], map.get(a[1]).toString()})
.collect(Collectors.toList());
用這個替換最后一個語句以消除重復。
out
= allRows.stream()
.map(a -> new String[]{a[0], a[1], map.get(a[1]).toString()})
.map(a -> Arrays.toString(a))
.distinct()
.map(s -> s.substring(1, s.length()-1).split(","))
.collect(Collectors.toList());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.