I am trying to filter the ArrayList of a Java object based on the value of an object variable.
Sorry if this sounds confusing. Perhaps the code will explain this better.
public static void main(String[] args)
{
ArrayList<Data> list = new ArrayList<>();
list.add(new Data("Uvumvew", 10));
list.add(new Data("Uvumvew", 10));
list.add(new Data("Uvumvew", 10));
list.add(new Data("Uvumvew", 11));
list.add(new Data("Uvumvew", 14));
list.add(new Data("Uvumvew", 14));
list.add(new Data("Ossas", 5));
list.add(new Data("Ossas", 5));
list.add(new Data("Ossas", 10));
list.add(new Data("Ossas", 10));
list.add(new Data("Ossas", 10));
list.add(new Data("Dummy", 7));
list.add(new Data("Dummy", 7));
list.add(new Data("Dummy", 7));
list.add(new Data("Dummy", 8));
list.add(new Data("Dummy", 8));
}
and object
private String name;
private double value;
public Data() {
}
public Data(String name, double value) {
super();
this.name = name;
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getValue() {
return value;
}
public void setValue(double value) {
this.value = value;
}
There will be duplicates in the archarist, as you can see. I can only filter it after it was an arraylist, since I read the files and then put them in an ArrayList.
The result that I am trying to achieve is as follows
Uvumvew,10
Ossas,10
Dummy,7
Since 10,10,7 are the most common value for Uvumvew, Ossas and Dummy respectively. I tried using Collection and filtering the value, but since the object has duplicate values, this is not possible.
My attempt looks like this:
Collection<Data> nonDuplicatedName = list.stream()
.<Map<String, Data>> collect(HashMap::new,(m,e)->m.put(e.getName(), e), Map::putAll)
.values();
it produces a result that is incorrect
Dummy 8.0
Uvumvew 14.0
Ossas 10.0
. !