I want to be able to add new entries of parameter inputs to the list.
For example:
public static void theList (List<String> wholeList) {
wholeList = new ArrayList<String>();
wholeList.add("Lettuce");
wholeList.add("Bacon");
wholeList.add("Milk");
wholeList.add(wholeList); <--------- error - addAll doesn't fix it.
Above I tried ' wholeList.add(wholeList) '. What I intended to do is: Whatever additional (item (from parameter), when adding the input to run this method) item I need to add, will be added to the ' wholeList '.
As you can see, I have 3 items added to the list: Lettuce, Bacon and Milk. However, if I suddenly changed my mind, and want to add another item (via parameter), I can simply add it to the current list (wholeList).
Also, another question.
Is there a neater way to add a list of items instead of adding it one-by-one (whilst using the same list import)? Say, {"Lettuce", "Milk", "Bacon", etc}?
TY.
As I understand, addAll() is everything you need:
List<String> someList = new ArrayList<String>();
List<String> itemsToAdd = new ArrayList<String>();
itemsToAdd.add("one");
itemsToAdd.add("two");
someList.addAll(itemsToAdd);
// or use handy method which creates temporary list internally:
someList.addAll(Arrays.asList("three", "four"));
Well, your code does something very wrong.
You initialize the wholeList inside the method, and after the method is finished, it is gone (pointers in Java).
Also, you added the list on itself, so the code is probably not what you wanted to do.
you probably meant to create a new list inside the method and add all the items to the list in the parameter.
If so, you shouldn't use "new" on the list that you got from a parameter.
Actually, after reading the title of your question -
You need an existing list - it can't be with the name of the list in the parameter. Let's call it existingList.
After you get the list in the method, you shouldn't use the "new ArralyList" on it, as it will void the list from the parameter.
Your code should look like that:
public static void theList (List<String> wholeList) {
wholeList.add("Lettuce");
wholeList.add("Bacon");
wholeList.add("Milk");
existingList.add(wholeList);
The only "cleaner" way of adding the values to the list would be:
wholelist.addAll(Arrays.asList("Lettuce", "Bacon", "Milk"));
But I see the Top answer already states that. So, you could clean it up more by creating a array as a global private variable outside of the method. Also, as another answer said, you should have another seperate list that does not share the same name as the parameter list. Here is an example with libaries needed:
import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
public class Example{
private List<String> globalList = new ArrayList<>();
private String[] list = {"Bacon", "Lettuce", "Milk"};
public static void theList (List<String> wholelist) {
wholelist.addAll(Arrays.asList(list));
globalList.addAll(wholeList);
}
If you wanted to use wholeList as the name for both lists, then you could change globalList above to wholelist, then:
public static void theList (List<String> wholelist) {
this.wholelist.AddAll(wholelist);
this.wholelist.addAll(Arrays.asList(list));
}
But I would avoid doing that.
Related
I'm new to JOOQ and currently fail to map a joined query to Map<K, List<V>>: the list always only contains one element.
Here's my code:
DSL.using(...)
.select(ORDER.fields())
.select(ORDER_ITEM_ARTICLE.fields())
.from(ORDER)
.leftOuterJoin(ORDER_ITEM_ARTICLE).on(ORDER.ID.eq(ORDER_ITEM_ARTICLE.ORDER_ID))
// to Map<InOutOrder, List<OrderItemArticle>>
.fetchGroups(
r -> r.into(ORDER).into(InOutOrder.class),
r -> r.into(ORDER_ITEM_ARTICLE).into(OrderItemArticle.class)
)
// map to InOutOrder
.entrySet().stream().map( e -> {
// e.getValue() always returns list with only 1 element?!
e.getKey().articles = e.getValue();
return e.getKey();
})
.collect(Collectors.toList())
;
Say I have 1 row in ORDER and 2 corresponding rows in ORDER_ITEM_ARTICLE. Running the SQL returned by .getSQL() (after .fetchGroups()), returns me 2 rows as expected, so I assumed the fetchGroups() call will populate my list with two entries as well?!
What am I missing?
Thanks!
Update:
As requested, the InOutOrder class:
public class InOutOrder extends Order {
public List<OrderItemArticle> articles;
public List<OrderItemOther> others;
public List<OrderItemCost> costs;
public List<OrderContact> contacts;
public List<EmailJob> emailJobs;
}
So this is just an extension of the JOOQ POJO class and is used for JSON communication with the API clients...
fetchGroups() simply puts objects in a LinkedHashMap. You have to adhere to the usual Map contract, which means implementing equals() and hashCode(). Without it, each object you're creating (or which jOOQ is creating for you) will use identity comparison, so you get every "value" only once in the result.
I have a map1 which holds the information as
[40256942,6] [60246792,5]
Now that I want to prepare a map2 that holds information such as
itemNo, 40256942
qty, 6
itemNo, 60246792
qty, 5
to prepare final information as json
“partialArticlesInfo”: [{itemNo:”40256942”, availQty:”6”}, {itemNo:”60246792”, availQty:”5”}]
I am trying to iterate map1 to retrieve values and set that against the key. But I am getting only one entry which is last one. Is there any way , I get the new map with entries such as mentioned above
Map<String, String> partialArticlesInfo = new HashMap<String,String>();
Map<String, String> partialArticlesTempMap = null;
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet())
{
partialArticlesTempMap = new HashMap<String,String>();
partialArticlesTempMap.put("itemNo",entry.getKey());
partialArticlesTempMap.put("availQty",entry.getValue());
partialArticlesInfo.putAll(partialArticlesTempMap);
}
In Java (I'm assuming you're using Java, in the future it would be helpful to specify that) and every other language I know of, a map holds mappings between keys and values. Only one mapping is allowed per key. In your "map2", the keys are "itemNo" and "availQty". So what is happening is that your for loop sets the values for the first entry, and then is overwriting them with the data from the second entry, which is why that is the only one you see. Look at Java - Map and Map - Java 8 for more info.
I don't understand why you are trying to put the data into a map, you could just put it straight into JSON with something like this:
JSONArray partialArticlesInfo = new JSONArray();
for (Map.Entry<String,String> entry : partialStockArticlesQtyMap.entrySet()) {
JSONObject stockEntry = new JSONObject();
stockEntry.put("itemNo", entry.getKey());
stockEntry.put("availQty", entry.getValue());
partialArticlesInfo.put(stockEntry);
}
JSONObject root = new JSONObject();
root.put("partialArticlesInfo",partialArticlesInfo);
This will take "map1" (partialStockArticlesQtyMap in your code) and create a JSON object exactly like your example - no need to have map2 as an intermediate step. It loops over each entry in map1, creates a JSON object representing it and adds it to a JSON array, which is finally added to a root JSON object as "partialArticlesInfo".
The exact code may be slightly different depending on which JSON library you are using - check the docs for the specifics.
I agree with Brendan. Another solution would be otherwise to store in the Set or List objects like the following.
class Item {
Long itemNo;
int quantity;
public int hashCode() {
Long.hashCode(itemNo) + Integer.hashCode(quantity);
}
public int equals(Object other) {
other instanceOf Item && other.itemNo == this.itemNo && other.quantity = this.quantity;
}
}
}
then you can use the JsonArray method described by him to get the Json string in output
This means that adding new variables to the object won't require any more effort to generate the Json
I want to design a view that display only projects of selected customer and services, so I created a view that customer and service columns are categorized and a view panel for this view. If I put
document1.getDocument().getItemValueString("Customer")
it works with a restrict single category. How I can do this with tow categorized columns.
Thanks in advance
Could you implement a repeat within a repeat for this?
The first repeat would capture your first category. Then inside you have a panel and a repeat and the second repeat would further filter the datasource by the second category
You cheat. Have one column that concatenates customer and project. Grab that column in your selection and split it in code.
Then use the selected value for the one column. Lets presume your original columns are customer and project. So your new column would have the formula customer+"~"+project. You then read this values to populate a SSJS object or a variable, so you can retrieve the customers (first dropdown) and the projects (second dropdown). In a dropdown you can use the format Display|Value, so a good approach is to have the value in the format customer~project.
As said you can do that in Java or JavaScript. Since I like Java's collection framework a lot, here's the Java version:
import java.util.Set;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
import lotus.domino.Database;
import lotus.domino.NotesException;
import lotus.domino.View;
import lotus.domino.ViewEntry;
import lotus.domino.ViewEntryCollection;
public class SplitCategoryBean {
private static final String SEPARATOR = "~";
private final Map<String,Set<String>> allCategories = new TreeMap<String, Set<String>>();
public void populate(Database db, String viewName) throws NotesException {
View v = db.getView(viewName);
ViewEntryCollection vec = v.getAllEntries();
ViewEntry ve = vec.getFirstEntry();
while (ve != null) {
ViewEntry nextVE = vec.getNextEntry(ve);
this.addEntry(ve.getColumnValues().get(0).toString());
ve.recycle();
ve = nextVE;
}
vec.recycle();
v.recycle();
}
private void addEntry(String combinedCategory) {
String[] splitCategory = combinedCategory.split(SEPARATOR);
String key = splitCategory[0];
String value = splitCategory[1];
Set<String> thisCategory = (this.allCategories.containsKey(key)) ? this.allCategories.get(key): new TreeSet<String>();
thisCategory.add(value+"|"+combinedCategory);
this.allCategories.put(key, thisCategory);
}
public Set<String> getFirstCategory() {
return this.allCategories.keySet();
}
public Set<String> getSecondCategoryReadyForDropDown(String key) {
return this.allCategories.get(key);
}
}
You would configure that as a managed bean (viewScope) and in the queryOpen you call the populate method. Then you can easily bind your first selection to #{beanName.firstCategory} for the selection and e.g. #{viewScope.curCustomer} for the value. The second drop-down you use the rendered="#{viewScope.curCustomer}" so it only shows when the customer is selected. And you bind the selections to #{javascript:beanName.getSecondCategoryReadyForDropDown(viewScope.curCustomer);
Put refreshs on the change events and render the view only if you have a project selected.
Does that work for you?
Thanks guys
I created a view that the first column is categorized and its value is Customer+Service then put
document1.getDocument().getItemValueString("Customer") + document1.getDocument().getItemValueString(“Service")
in "filter by category name" of view panel it works now.
I have just started utilizing ArrayLists in some C# code and am having some problems when sorting.
First I define create an ArrayList object under my class:
ArrayList cutList = new ArrayList;
Then I set and sort the array list to find the minimum:
cutList.Add("2200","1800","1200","1");
int minList = (int)GetMinValue(cutList);
Using the function:
public static object GetMinValue(ArrayList arrList)
{
ArrayList sortArrayList = arrList;
sortArrayList.Sort();
return sortArrayList[0];
}
Later I try to find the index cutList[2] and I find "1200" because the function also sorted cutList. I have also had the same problem in the past, when I set a variable to an Application settings and then the Applications setting changes when I modify the variable. How to I correctly fix these problems. I have been learning C# on my own and am guilty of skipping around a little bit. Is there a lesson on Objects that I am missing?
The issue in your code is that ArrayList sortArrayList = arrList; does not copy arrList to sortArrayList: the assignment merely creates a new alias for the existing object. To make your code work, use
ArrayList sortArrayList = (ArrayList)arrList.Clone();
I must add that this is probably the most inefficient way of looking up the min element in a list, and also a rather archaic container. I would prefer using List<string> instead of ArrayList, and using LINQ's Min() function to get the minimum element.
Using Automapper, how do you handle the mapping of a property value on an object to an instance of a string. Basically I have a list of Role objects and I want to use Automapper to map the content of each "name" property to a corresponding list of string (so I just end up with a list of strings). I'm sure it has an obvious answer, but I can't find the mapping that I need to add to "CreateMap" to get it to work.
An example of the relevant code is shown below:
public class Role
{
public Guid Id{get;set;}
public string Name{get;set;}
...
...
}
// What goes in here?
Mapper.CreateMap<Role, string>().ForMember(....);
var allRoles = Mapper.Map<IList<Role>, IList<string>>(roles);
I love Automapper (and use it in a number of projects), but wouldn't this be easier with a simple LINQ statement?
var allRoles = from r in roles select r.Name
The AutoMapper way of accomplishing this:
Mapper.CreateMap<Role, String>().ConvertUsing(r => r.Name);