- this creates a
List of some instances (records) that have duplicate values in the array for similar names.
- It uses a hashMap to store the name and domain by taking advantage of
computeIfAbsent to first create the set if it doesn't exist, otherwise, add the arrays to it. The purpose of the set is to eliminate duplicates.
// your list of objects each with a name and Integer[] domain
List<Variable> vars = List.of(new Variable("var1", 1, 2, 3),
new Variable("var2", 4, 5, 6), new Variable("var1", 1, 9, 10),
new Variable("var5", 1, 6, 8), new Variable("var2", 4, 8, 9));
Map<String, Set<Integer>> result = new HashMap<>();
for (Variable v : vars) {
result.computeIfAbsent(v.name, k -> new HashSet<>())
.addAll(Arrays.asList(v.domain));
}
result.entrySet().forEach(System.out::println);
prints
var5=[1, 6, 8]
var2=[4, 5, 6, 8, 9]
var1=[1, 2, 3, 9, 10]
The Variable class per your description.
class Variable {
private String name;
private Integer[] domain;
public Variable(String name, Integer... domain) {
super();
this.name = name;
this.domain = domain;
}
public String getName() {
return name;
}
public Integer[] getDomain() {
return domain;
}
}
You can also do it using streams. I chose to use the flatMapping collector to combine the domain arrays into a set for each name.
Map<String,Set<Integer>> result = vars.stream().collect(
Collectors.groupingBy(v->v.getName(),
Collectors.flatMapping(
v->Arrays.stream(v.getDomain()),
Collectors.toSet())));
This yields the same as above. Both of the above examples assume an Integer array to hold the domain items. A List<Integer> would be even better. Primitive arrays aren't readily supported by Arrays.asList or stream operations but there are workarounds.
Varin your example. That impacts any help that we might provide. Please clarify.