Display duplicate attribute values once in Java object list - java

I have a list of java objects as below
I want to convert it to a list with 'Camera flash faulty' and 'Camera Housing Damaged' only once for the first object, like the one below.
Is there something that can be done with the solution mentioned here ?
Remove duplicates from a list of objects based on property in Java 8

You can add all the properties to a Set (Sets don't allow duplicates), if the value is already in the set, the method add returns false, so you can set to empty the property in the object:
Set<String> values = new HashSet<>();
for (MyObject obj : myList) {
if (!values.add(obj.getValue())) {
obj.setValue("");
}
}
Another alternative is to group all object with the same attribute value, then skip the first element of each group and set the attribute value to empty for all other objects in the group:
myList.stream()
.collect(Collectors.groupingBy(MyObject::getValue))
.forEach((k, v) -> v.stream().skip(1).forEach(o->o.setValue("")));

I am taking an example of Employee which have some duplicate id's.
Lets say you have a list as
List<Employee> employee
Add them into HashSet, which does not allow duplicates.
HashSet<Object> seen=new HashSet<>();
employee.removeIf(e->!seen.add(e.getID()));

Related

How to remove an element from a set that is in a map

I'm trying to remove an element from a set that is in a map but I'm unsure how to do it.
The code I have so far is:
public void deleteToValue(String aLocation, String aEquipment)
{
locationMap.remove(aLocation, aEquipment);
}
The map key is the location and the the set is called equipment.
Assume the location is London and I want to remove a bike from the set.
The key and set will always be present so there's no need to check for nulls at this point.
This requires 2 steps:
Set<String> equipment = locationMap.get(aLocation) => returns the set
equipment.remove(aEquipment) ==> removes equipment from set.
If I understood you correctly, you have a map -> Map<String, Set<String>> and you want to remove equipment for some location.
Please, consider this code:
public void deleteToValue(String aLocation, String aEquipment)
{
Set<String> equip = locationMap.get(aLocation);
if (equip != null) {
equip.remove(aEquipment);
}
}
When calling map .get(..key..) method, it returns a value associated with a provided key, in your case, your value is Set<>.
So, to remove something from the set, firtly you need to read it from the map by key -> Set<String> equip = locationMap.get(aLocation); and then remove the required item from the Set -> equip.remove(aEquipment);

How can I obtain the list of values for a given key and add the list of values to a newly created list?

So I'm going crazy with this one. This is for an assignment and can't seem to get this to work at all!!
I have the following HashMap:
HashMap<String, ArrayList<Team>> teams;
(Team being another class to obtain the details of the teams)
What I need to be able to do is get the List of teams for the Key(String) from the above HashMap, and assign the List to a local variable I have declared:
List<Team> results = teams.get(division);
But this is where I get stuck. I have no idea how I'm suppose to complete this task.
As a further note "division" is the Key used in the HashMap. The ArrayList is a list of teams that belong to the division.
I have tried the below, which does not compile at all. Really not sure how I can get this to work!!
public void recordResult(String division, String teamA, String teamB, int teamAScore, int teamBScore)
{
List<Team> results = teams.get(division);
for (String i : teams.keySet())
{
results = new ArrayList<Team>();
results.add();
}
}
**You can ignore the arguments after the "String division". These will be used later.
Iterate over the entrySet() of the Map. Now you can fetch each List for that specific key and proceed further. Something like:
for (Entry<String, ArrayList<Team>> entry : teams.entrySet()) {
// extract the value from the key using `teams.get(entry.getKey())`
// proceed further with the value obtained
}

Iterate ArrayList through Hashmap to find unused element

Trying to make an application User management system and suddenly came to a problem. I have an ArrayList of groups f.e. {Group1, Group2, Group3}. If I assign user to one group I put it into HashMap where {key, value} is {user, group}. And if no user is assigned to group, when I want to delete this group. How to find out which of the group wasn't used?
Suppose you have ArrayList<Group> groups and HashMap<User, Group> userMap then you can find the group with no user with:
Set<Group> mappedGroup = new HashSet<>(userMap.values());
groups.removeIf(mappedGroup::contains); /? After this `groups` is unmapped groups list
The precondition is Group class already implement equals/hashcode
If you don't want to modified your original groups list, then you can do:
List<Group> unmappedGroups = groups.stream().filter(g -> !mappedGroup.contains(g))
.collect(Collectors.toList());
Convert the map values to a HashSet for constant time look up like following
    
Set<String> usedGroups = new HashSet<>(map.values());
Then checking can be done in the following way
for (String group : list) {
if (usedGroups.contains(group)) { ... }
}

Java: Searching for an entry in a List of Objects only by one attribute

I have the following List
List<A> list= new ArrayList<>();
public class A{
private String name;
private List<B> listB = new ArrayList<>(); }
I now want to search for an entry in list by which I only identify by it's name. The background is, that I get an Object of A which I want to add in listB. To make it more nice, I want to search if there is already a entry with this name in A and then add the entries which are given to the method there:
Example in text:
list:
name1
entry11
etnry12
entry13
name2
entry21
entry22
Now I want to Add the following listB to listA
name1
entry14
entry15
Behaviour now:
list:
name1
entry11
etnry12
entry13
name2
entry21
entry22
name1
entry14
entry15
Desired bahaviour:
list:
name1
entry11
etnry12
entry13
entry14
entry15
name2
entry21
entry22
Why not using a Set<A> instead of List<A> as the name should be unique for each instance of A in the collection ?
To achieve your need, you could override equals() and hashcode() method in A by relying on the the name field.
In this way, when you want to add elements from a list of A with a specific label to a list of A with this same specific label, you could create a A object with the expected name and retrieve it from the both lists.
Here is a sample code :
String name = "nameFromObjectWhereIWantToAddElements";
A aToSearch = new A(name);
A targetA = listTarget.get(listTarget.indexOf(aToSearch));
A originaA = listOrigin.get(listOrigin.indexOf(aToSearch));
targetA.addElements(originaA.getElements());
You could also use a Map if the structure suits to your needs.
A list with a key for the value has a data structure Map. Instead of using array list you can use Map to take the advantages of the JavaSE API.
You can use this method to do so if you use map. "A Set is a Collection that cannot contain duplicate elements." for more info refer to here.
public static void add(Map<String, HashSet<String>> listB) {
for (String entry : listB.keySet()) {
if (listA.containsKey(entry)) {
listA.get(entry).addAll(listB.get(entry));
} else {
listA.put(entry, listB.get(entry));
}
}
}
NOTE: I used Set to remove duplicate entries as the values for the keys. if you want to keep duplicate you can use ArrayList<>(). Moreover, Set do not keep the order beased on some implimentations and the order of the entries may vary time to time.

How to get the common field from a list of object

Say I have a class of Student contain in fields : firstName and surname
I then use this to create two lists
List<Student> classroomA = {["Ben","oreilly"], ["Jenna","Birch"]}
List<Student> classroomB = {["Alan","Messing"], ["Ben", "Mancini"], ["Helena","Wong"]}
How would I go about using these lists to get all Students with same name from the list :
List<Student> commonStudents = {["Ben","oreilly"],["Ben", "Mancini"]}
Would doing for loop on both list and doing a classroomA.getfirstName().equals(classroomB.getfirstName())
the only way ?
Use Java 8 Lambdas.
Below code gets all Bens from the list. If you want a particular field from the object (which is transformation), then use the map on filter stream.
List<Student> AllBens = classA.stream().filter(Objects::nonNull).
filter(k -> StringUtils.isNotEmpty(k.getName()) && k.getName().equalsIgnoreCase("Ben")).collect(Collectors.toList());

Categories