How do I add a list of things into a set?
When I do set.addAll I get an error
required type :Collection <? extends List>
provided type :List
public static Set<List<Food>> getAllMealPlans(Set<Food> foods, int numMeals) {
Set<List<Food>> set = new HashSet<>();
List<Food> aList = new ArrayList<Food>(foods);
List<Food> sortedList = aList.stream().sorted(Comparator.comparing(a -> a.meal)).collect(Collectors.toList());
set.addAll(sortedList);
Set<List<Food>> set = new HashSet<>();
This set object is a Set of List s. This means every item in the set is a List<Food>.
How do I add a list of things into a set?
As you want to create a Set which contains multiple lists, you can simply use set.add(). This will insert the sortedList as an item in the set which will end up what you are looking for.
set.add(sortedList);
When to use addAll()?
Adds all of the specified elements to the specified collection.
Elements to be added may be specified individually or as an array.
https://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#addAll(java.util.Collection,%20T...)
Possible enhancements
As you are already using java stream, I will get rid of aList variable like below.
List<Food> sortedList = foods.stream().sorted(Comparator.comparing(a -> a.meal)).collect(Collectors.toList());
You can actually remove stream operations. First collect set items to a List object and then perform sorting with a method references in your comparator.
List foodList = new ArrayList(set);
foodList.sort(Comparator.comparing(Food::meal));
Related
I'm trying to understand a very basic concept and I'm not sure why it doesn't work.
I have two lists of type, and I want to combine them into one Set with distinct values (as it should be by the definition of Set). However, when I print the set values I get duplicates.
List<SID> list1 = (.....)
List<SID> list2 = (.....)
Set<SID> combined = new HashSet<>();
combined.addAll(list1);
combined.addAll(list2);
I also tried with distinct()
Set<SID> combinedSet = Stream.concat(list1.stream(), list2.stream()).distinct().collect(Collectors.toSet());
List<SID> combinedList = Stream.concat(list1.stream(), list2.stream()).distinct().collect(Collectors.toList());
Any idea why?
SID class overrides the hashCode and the equals method...any other way to achieve it?
I have created two lists object from the same pojo and sorted one of them. When I tried to change one list, other lists also got updated.
List<FilterPojo.Data> filterList = new ArrayList<>();
List<FilterPojo.Data> subFilterList = new ArrayList<>();
If I change the value in filterList, same changes occur in subFilterList
With the limited information that is provided by you, it seems you are creating/populating subFilterList as subList of filterList. When you do that, all changes made in either of the list will be reflected in other.
This happens because List.subList(), returns a view of the list, so modifications to the original list will be reflected in the sub-list. As suggested by others, instead of subList use addAll to populate subFilterList
This could be reference problem. Lists maintains their references when items are copied to other list, if you do something like:
List<FilterPojo.Data> subFilterList = filterList;
Use addAll method instead,
subFilterList.clear();
subFilterList.addAll(filterList);
Try below
List<String> filterList = new ArrayList<String>();
List<String> subFilterList = new ArrayList<String>();
filterList.add("A");
filterList.add("B");
filterList.add("C");
/*subFilterList = filterList; // reference to same object , change will reflect in both
filterList.add("C");
System.out.println(filterList);
System.out.println(subFilterList);*/
subFilterList.addAll(filterList);
filterList.add("C");
System.out.println(filterList);
System.out.println(subFilterList);
I don't know exactly the context that you are asking.
Your lists are holding the same object. For example, in this case p1.
Person p1 = new Person();
List<Person> list1 = new ArrayList<Person>();
list1.add(p1);
List<Person> list2 = new ArrayList<Person>();
list2.add(p1);
p1.setName("new name");
I have three ArrayLists:
One is used for storing user input in the order they were entered, located in the main class.
Second one is exactly the same as the first one, but it is passed into a method called remTrip to be copied and will return the result.
Third one is list1 in the code below, which is the one being processed.
public static ArrayList<String> remTrip( ArrayList<String> a){
//code here
ArrayList<String> list1 = a;
Collections.sort(list1);
//code to remove triplicates from the list and returns the result
}
I wanted to keep the first ArrayList<String> in the same order it was (i.e. {"dog", "cat" , "tiger", "cat", "cat"} ), but apparently the Collections.sort() sorts all of the ArrayLists.
How do I sort only one of the list and not the others?
The problem is not how Collections.sort() works. The problem is that instead of creating a copy of your list, you set the new list equal to your list. This means that they both point to the same object, sorting one will sort the other because they are the same thing. To solve this set list1 to a copy of a instead of setting them equal.
You should be able to do
ArrayList<String> list1 = new ArrayList<String>(a);
Three arralists you're talking about are not 3 different arraylists. They're just three different references to the same arraylist.
What you're doing essentially is -
List list01 = new ArrayList();
List list02 = list01;
List list03 = list01;
What you want is -
List list01 = new ArrayList();
List list02 = new ArrayList(list01);
List list03 = new ArrayList(list01);
But you should remember, this way will give you a copy of your List, not all it's elements. So, if you change one of the elements in your copied List, it will be changed in your original List too.
How to solve it - Hint copy constructor.
I am trying to declare an array of Set<String> so I do not have to manage each sets separately. But things go wrong:
ArrayList<Set<String>> categories=new LinkedHashSet<>();
Here, Java says that type Set<String> is erroneous and then reports an error.
If this is wrong, then how can I make an array of :
static Set<String> category1 = new LinkedHashSet<>();
You are initialising an ArrayList with LinkedHashSet object and hence the error:
ArrayList<Set<String>> categories=new LinkedHashSet<>();
change it to
ArrayList<Set<String>> categories=new ArrayList<>();
you need to use HashSet when you create a Set to be added into the list. Something like this:
Set<String> firstSet = new HashSet<String>();
//build your set
//add set to list
categories.add(firstSet);
Btw, you mentioned Array in your question description, so here is the declaraiton for plain array of Sets:
Set<String>[] categories=new HashSet[10];
You can do something like:
List<HashSet> list =new ArrayList<HashSet>();
HashSet<String> hs =new HashSet<String>();
hs.add(value1);
hs.add(value2);
list.add(hs);
You can use for or while loop to add values to set(hs) and then add the set to list.
I am implementing a Java class responsible for ordering java.util.List. The problem comes when I use this class. I'm able to ordering the list but I want to copy the "original" list without modification so that I could register every change made on the original list. The sorted list contains object and one of its fields stores a classification id, and this id it is updated with the index value of the list.
I tried to use clone method and it keeps the list unsorted but the changes made on original list are updated in the clone list too.
Is there any way to accomplish it?
My Code:
List<Torero> listaTorero = tbTlgTorerolHome.findByExample(new Torero());
List<Torero> listaToreroTemp = ((List<Torero>) ((ArrayList<Torero>) listaTorero).clone());
Clasificacion clasificacion = new Clasificacion();
Iterator<Torero> iterTorero = clasificacion.getClasificacion(listaTorero, torero).iterator(); //Sorting List
A Clasificacion method:
public List<Torero> getClasificacion(List<Torero> listaToreroTemp, Torero torero)
{
List<Torero> listaTorero = new ArrayList<Torero>();
Collections.sort(listaToreroTemp,new ToreroClasifiacionComparator());
Iterator<Torero> iterTorero = listaToreroTemp.iterator();
int index=1;
while(iterTorero.hasNext())
{
Torero toreroTemp = iterTorero.next();
toreroTemp.setNumClasificacion(index);
listaTorero.add(toreroTemp);
index=index+1;
}
return listaTorero;
}
You may create a new list with an input of a previous list like so:
List one = new ArrayList()
//... add data, sort, etc
List two = new ArrayList(one);
This will allow you to modify the order or what elemtents are contained independent of the first list.
Keep in mind that the two lists will contain the same objects though, so if you modify an object in List two, the same object will be modified in list one.
example:
MyObject value1 = one.get(0);
MyObject value2 = two.get(0);
value1 == value2 //true
value1.setName("hello");
value2.getName(); //returns "hello"
Edit
To avoid this you need a deep copy of each element in the list like so:
List<Torero> one = new ArrayList<Torero>();
//add elements
List<Torero> two = new Arraylist<Torero>();
for(Torero t : one){
Torero copy = deepCopy(t);
two.add(copy);
}
with copy like the following:
public Torero deepCopy(Torero input){
Torero copy = new Torero();
copy.setValue(input.getValue());//.. copy primitives, deep copy objects again
return copy;
}
Use the ArrayList copy constructor, then sort that.
List oldList;
List newList = new ArrayList(oldList);
Collections.sort(newList);
After making the copy, any changes to newList do not affect oldList.
Note however that only the references are copied, so the two lists share the same objects, so changes made to elements of one list affect the elements of the other.