[英]Average of values based on distinct ID by Java Stream
我有一堂課叫做Tag。
public class Tag {
String tag_id;
int x_pos;
int y_pos;
int z_pos;
public String getTag_id() {
return tag_id;
}
public void setTag_id(String tag_id) {
this.tag_id = tag_id;
}
public int getX_pos() {
return x_pos;
}
public void setX_pos(int x_pos) {
this.x_pos = x_pos;
}
public int getY_pos() {
return y_pos;
}
public void setY_pos(int y_pos) {
this.y_pos = y_pos;
}
public int getZ_pos() {
return z_pos;
}
public void setZ_pos(int z_pos) {
this.z_pos = z_pos;
}
public String toString()
{
return this.tag_id +" "+this.x_pos+" "+this.y_pos+" "+this.z_pos;
}
}
現在,我有了一個標簽的數組列表。
ArrayList<Tag> tag_info = new ArrayList<>();
標簽ID可以是A,B,C或其他任何內容。 它是動態的,不是固定的。 我需要獲取tag_info的x_pos,y_pos和z_pos的tag_info
。 數組列表的大小也是動態的,范圍在60-70之間。 我已經使用循環編寫了所有內容,但想使用Stream對其進行轉換。
我使用以下方法提取了唯一的ID:
Stream<Tag> a = tag_info.stream().filter(distinctByKey(Tag::getTag_id));
但是現在我不想對所有值進行循環並獲得平均值。 有沒有更簡單的方法?
Double xAvg = tag_info.stream()
.collect(Collectors.averagingDouble(Tag::getX_pos));
Double yAvg = tag_info.stream()
.collect(Collectors.averagingDouble(Tag::getY_pos));
Double zAvg = tag_info.stream()
.collect(Collectors.averagingDouble(Tag::getZ_pos));
另外,如果您想通過每個tag_id
獲取平均值, tag_id
使用groupingBy
:
Map<String, Double> map = tags.stream()
.collect(groupingBy(Tag::getTag_id,
averagingDouble(Tag::getX_pos)));
也許緩存total可以幫助避免重新計算所有值,例如:
long total_x
long total_y
long total_z
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.