Group a list of objects by an attribute
This will add the students object to the HashMap
with locationID
as key.
HashMap<Integer, List<Student>> hashMap = new HashMap<Integer, List<Student>>();
Iterate over this code and add students to the HashMap
:
if (!hashMap.containsKey(locationId)) {
List<Student> list = new ArrayList<Student>();
list.add(student);
hashMap.put(locationId, list);
} else {
hashMap.get(locationId).add(student);
}
If you want all the student with particular location details then you can use this:
hashMap.get(locationId);
which will get you all the students with the same the location ID.
using java 8 to group list of object by object attribute of type list: JAVA
Take a look here and here
This code fragment create 3 users, like in your example.
var users = Arrays.asList(
new User("1", Arrays.asList("10", "20", "30")),
new User("2", Arrays.asList("10", "50")),
new User("3", Arrays.asList("10", "80")));
Map<String, Long> result = users
.stream()
.flatMap(user -> user.getBrand_ids().stream())
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(result);
// Result is: {80=1, 50=1, 30=1, 20=1, 10=3}
How to group objects in a list with object property in Java
If we can return a Map<String, List<Item>>
, where the key is the team
and the value is a List<Item>
belonging to that team, we can use
final Map<String, List<Item>> itemsByTeam =
items.stream().collect(Collectors.groupingBy(item -> item.team));
Ideone demo
Remark: This solution was first posted in a comment by another user and they deleted the comment shortly after. I do not remember the user's name. If they post an answer, I will delete mine. If they do not want to post an answer, but contact me, I will credit them by name.
A comment on the code: I would recommend to introduce getters for the attributes since the stream
-operation is most likely to be called outside of class Item
itself, hence attribute team
will not be visible. Also, this would lead to an implementation like
final Map<String, List<Item>> itemsByTeam =
items.stream().collect(Collectors.groupingBy(Item::getTeam));
which may or may not be regarded as "more pleasing" to the reader.
Group list of object by an attribute and set other remaining attribute to different object list : Java 8 stream and Lambdas
The result should be List<StudentSubject>
in your case you can use this way :
List<StudentSubject> resultList = studentList.stream()
.collect(Collectors.groupingBy(Student::getId)) // until this point group by Id
.entrySet() // for each entry
.stream()
.map(s -> new StudentSubject( // create a new StudentSubject
s.getValue().get(0).getName(), // you can use just the name of first element
s.getValue().stream() // with a list of Result
.map(r -> new Result(r.getSubject(), r.getScore()))
.collect(Collectors.toList()))
).collect(Collectors.toList()); // then collect every thing as a List
Outputs
StudentSubject{name='John', results=[Result{subjectName='Math', score=80}, Result{subjectName='Physics', score=65}]}
StudentSubject{name='Thomas', results=[Result{subjectName='Computer', score=55}, Result{subjectName='Biology', score=70}]}
How to group a list of tuples/objects by similar index/attribute in python?
defaultdict
is how this is done.
While for
loops are largely essential, if
statements aren't.
from collections import defaultdict
groups = defaultdict(list)
for obj in old_list:
groups[obj.some_attr].append(obj)
new_list = groups.values()
Group a list inside an object by multiple attributes : Java 8
I would add the following method to Result
:
Result addOccurrences (List<Occurrences> occurrences) {
this.occurrences.addAll (occurrences);
return this;
}
And then you can use Streams:
List<Result> collect = results.stream ()
.collect (Collectors.groupingBy (Result::getId, Collectors.groupingBy (Result::getName, Collectors.toList ())))
.values ()
.stream ()
.map (Map::values)
.flatMap (Collection::stream)
.map (Collection::stream)
.map (resultStream -> resultStream.reduce ((r0, r1) -> r0.addOccurrences (r1.getOccurrences ())))
.filter (Optional::isPresent)
.map (Optional::get)
.collect (Collectors.toList ());
Related Topics
How Does a Arraylist's Contains() Method Evaluate Objects
Why Can't Overriding Methods Throw Exceptions Broader Than the Overridden Method
Executorservice, How to Wait for All Tasks to Finish
How to Call the Default Deserializer from a Custom Deserializer in Jackson
How to Deploy a Javafx 11 Desktop Application with a Jre
Java.Lang.Classnotfoundexception: Com.Mysql.Jdbc.Driver in Eclipse
How to Import a Class from Default Package
Java "Void" and "Non Void" Constructor
How to Maintain Jtable Cell Rendering After Cell Edit
What's the Difference Between Concurrenthashmap and Collections.Synchronizedmap(Map)
Compiling a Java Program into an Executable
How to Monitor the Computer's Cpu, Memory, and Disk Usage in Java
Concatenating Null Strings in Java
Splitting on Comma Outside Quotes
How to Specify Jackson to Only Use Fields - Preferably Globally
If Profiler Is Not the Answer, What Other Choices Do We Have