How to avoid duplicate values in a JComboBox? - java

cmbMake = new JComboBox();
cmbMake.addItem("**Please Select**");
Iterator i = products.entrySet().iterator();
while (i.hasNext())
{
Map.Entry me = (Map.Entry) i.next();
Product p = (Product) me.getValue();
if(!p.getMake().equals(cmbMake.getSelectedItem()))
{
cmbMake.addItem("" + p.getMake());
}
}
I have a class which holds product details is there anyway to stop the same make being added to the combo box?

You can try this code (I added some code to yours). The code gets the values of makes and stores them in a Set collection, and then populates the combo box.
cmbMake = new JComboBox();
cmbMake.addItem("**Please Select**");
Iterator i = products.entrySet().iterator();
Set<String> uniqueMakes = new HashSet<>(); // this stores unique makes
while (i.hasNext())
{
Map.Entry me = (Map.Entry) i.next();
Product p = (Product) me.getValue();
//if(! p.getMake().equals(cmbMake.getSelectedItem()))
//{
// cmbMake.addItem("" + p.getMake());
//}
uniqueMakes.add(p.getMake());
}
System.out.println(uniqueMakes); // this prints the makes
// Add makes to the combo box
for (String make : uniqueMakes) {
cmbMake.addItem(make);
}
Suggestions: You can use type parameters while using some of these, for example:
JComboBox<String> cmbMake = new JComboBox<>();
Iterator<Product> i = products.entrySet().iterator();
EDIT: Here are tutorials on using Set collection and using Generics.
EDIT (another way of coding the same functionality using functional-style programming):
cmbMake = new JComboBox<String>();
cmbMake.addItem("**Please Select**");
products.values()
.map(product -> product.getMake())
.collect(Collectors.toCollection(HashSet::new))
.forEach(make -> cmbMake.addItem(make));

Add all values to a Set and iterate over it :
for(Object o : new HashSet<>(products.values())){
Product p = (Product) o.getValue();
if(!p.getMake().equals(cmbMake.getSelectedItem())) {
cmbMake.addItem("" + p.getMake());
}
}

Assuming make is String, just create a set with all the different values and then add them to the ComboBox:
Set<String> productMakes = new HashSet<String>();
for (Map.Entry<KeyClass, Product> productEntry: products.entrySet()) {
productMakes.add(productEntry.getValue().getMake());
}
// How about sorting the items before adding them to the ComboBox?
List<String> sortedProductMakes = new ArrayList<String>(productMakes);
java.util.Collections.sort(sortedProductMakes);
for (String productMake : sortedProductMakes ) {
cmbMake.addItem(productMake);
}

Try this code,
cmbMake = new JComboBox();
cmbMake.addItem("**Please Select**");
Map products = null;
Iterator i = products.entrySet().iterator();
while (i.hasNext()) {
Map.Entry me = (Map.Entry) i.next();
Product p = (Product) me.getValue();
Set<String> productSet = new HashSet<String>();
productSet.add(p.getMake());
if (!p.getMake().equals(cmbMake.getSelectedItem())) {
if (productSet.size() > 0) {
productSet.forEach(action -> {
cmbMake.addItem("" + action);
});
}
}
}

Related

JSF / Xpages how to clear sessionscopes?

I want to clear the current sessionscopes in my xpages application and reload them again. I have tried:
public Map<String, Object> sesScope;
this.sesScope = JSFUtil.getSessionScope();
clearMap(sesScope);
private void clearMap(Map<String, Object> map ){ // Get iterator for the keys
String methodName = new Object(){}.getClass().getEnclosingMethod().getName();
utils.printToConsole(this.getClass().getSimpleName().toString() + " " + methodName);
utils.printToConsole("-------before removing------");
utils.printToConsole(map.toString());
Set keyset = map.keySet();
Iterator itr = keyset.iterator();
while (itr.hasNext()) {
itr.next();
itr.remove();
}
utils.printToConsole("--------After removing-------");
utils.printToConsole(map.toString());
}
Somehow I can not simply say sesScope.clear() since that would result in an error:
java.lang.UnsupportedOperationException at
com.sun.faces.context.BaseContextMap.clear(ExternalContextImpl.java:392)
How do I clear the sessionscope properly?
I do this to clear sessionScope:
for (final String key : JSFUtil.getSessionScope().keySet()) {
JSFUtil.getSessionScope().remove(key);
}

Map.computeIfPresent() to initialize a List in Java

I have the following code:
for (String val: values) {
EnumType type = EnumType.get(val);
if (type != null) {
String key = type.name();
if (key.equals("camp2"))
key = "camp1";
ArrayList<String> tempList= mapN.get(key); //1
if (tempList == null) { // 2
tempList = new ArrayList<>();
}
tempList.add(val);
mapN.put(key, tempList); //3
}
}
where mapN, and valies are:
private Map<String, ArrayList<String>> mapN
ArrayList<String> values
type is an enum
And I have sonar, and sonar tell me that in the values with // 1,2,3 I need to use:
Map.computeIfPresent()
But I have reading about this topic, and I didn't find the way to change my code.
Who can help me?
I guess you can shorten that to:
values.forEach(val -> {
EnumType type = EnumType.get(val);
if(type != null){
String key = type.name();
if (key.equals("camp2"))
key = "camp1";
mapN.computeIfAbsent(key, x -> new ArrayList<>()).add(val);
}
});
A modified version of #Eugene's answer yields:
values.forEach(val -> Optional.of(val)
// get corresponding type, if it exists
.map(EnumType::get)
// get key
.map(EnumType::name)
// handle key == "camp2" scenario
.map(key -> key.equals("camp2")
? "camp1"
: key
)
// add val to map value list
.ifPresent(key -> mapN.computeIfAbsent(
key,
x -> new ArrayList<>()
).add(val))
});

How to retrieve word after specific word in Java?

I've this kind of String:
{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}
and i want to get a list of all words after cc=.
How can i do it? I'm not very confident with regex stuff.
public static void main(String[] args) {
String input = "aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3";
String[] splitValues = input.split(", ");
Map<String,List<String>> results = new Hashtable<>();
List<String> valueList = null;
// iterate through each key=value adding to the results
for (String a : splitValues) {
// a = "aa=bbbb" etc
String[] keyValues = a.split("=");
// you can check if values exist. This assumes they do.
String key = keyValues[0];
String value = keyValues[1];
// if it is already in map, add to its value list
if (results.containsKey(key)) {
valueList = results.get(key);
valueList.add(value);
} else {
valueList = new ArrayList<>();
valueList.add(value);
results.put(key, valueList);
}
}
System.out.println("cc= values");
valueList = results.get("cc");
// assumes value is in results
for (String a : valueList)
System.out.println(a);
}
Your question is very vague but I am guessing the String is provided as is, like:
String toSearch = "{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}";
By list I am guessing you are referring to the abstract List object and not to an array. Here is a solution:
String toSearch = "{aa=bbbb, cc=blabla1, ee=ffff, cc=blabla2, gg=hhhh, cc=blabla3,.......}";
List<String> result = new ArrayList<String>();
int prevMatch = 0;
while (toSearch.indexOf("cc=", prevMatch+1) != -1) {
result.add(toSearch.substring( // Substring method.
toSearch.indexOf("cc=",prevMatch+1)+3,toSearch.indexOf(",") //Getting correct indexes.
));
prevMatch = toSearch.indexOf("cc=",prevMatch+1);
}
The prevMatch variable ensures that the indexOf("cc=") that will be returned will be the next one occurring in the String. For the above String the returning ArrayList will contain the words "blabla1","blabla2", "blabla3" and whatever else is encountered.

How to Iterate over too big ArrayList<String>?

I have two ArrayList sourceMessageList and TargetMessageList. I need to compare both the message list data.
Now lets say List1 - 100 Records. List2 - 1000 records
From List1- 1st record is compared with each record in list2 and then List1- 2nd record is compared with each record in list2.
But list2 is getting the value hasNext() to true for 1st source data in list1.
private void compareMessageList(ArrayList<String> source_messageList, ArrayList<String> target_messageList)
throws Exception {
// TODO Auto-generated method stub
Iterator<String> sourceMessageIterator = source_messageList.iterator();
Iterator<String> targetMessageIterator = null;
while (sourceMessageIterator.hasNext()) {
String sourceMessage = (String) sourceMessageIterator.next();
targetMessageIterator = target_messageList.iterator();
while (targetMessageIterator.hasNext()) {
String targetMessage = (String) targetMessageIterator.next();
if (getCorpValue(sourceMessage).equalsIgnoreCase(getCorpValue(targetMessage))) {
assertXMLEquals(convertSwiftMessageToXML(sourceMessage), convertSwiftMessageToXML(targetMessage));
}
}
}
if (buffer.toString().length() > 0) {
writeDifferenceTofile(buffer.toString());
buffer.delete(0, buffer.length());
throw new CatsException("There are some differences in the files.");
}
System.out.println("Exiting now ...");
}
The above code is taking too much time to execute.
To speed things up:
HashMap<String, String> lowers = new HashMap<String, String>();
for (String source : source_messageList) {
lowers.put(getCorpValue(source).toLowerCase(), source);
}
for (String target : target_messageList) {
final String corpTarget = getCorpValue(target).toLowerCase();
if(lowers.containsKey(corpTarget)) {
assertXMLEquals(
convertSwiftMessageToXML(lowers.get(corpTarget)),
convertSwiftMessageToXML(target)
);
}
}

ArrayList displaying only the last value of index

public ArrayList getEmpInfo(int id) {
ArrayList data = new ArrayList();
loginPojo lp=new loginPojo();
EmployeeInfoPojo emp_info = new EmployeeInfoPojo();
Session session = null;
SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
session = sessionfactory.openSession();
String sql_query = "from loginPojo where id!=" + id;
Query query = session.createQuery(sql_query);
List<loginPojo> list = query.list();
Iterator it = list.iterator();
while (it.hasNext()) {
lp = (loginPojo) it.next();
emp_info.setName(lp.getName());
System.out.println("Before "+emp_info.getName());
data.add(emp_info);
System.out.println("After "+emp_info.getName());
}
return data;
}
This is the code for getting the information from the database using the hibernate framework.I tried to display the ArrayList in the main using the following code.
public static void main(String args[]) {
EmployeeInfoPojo emip = null;
EmployeeInfo emi = new EmployeeInfo();
ArrayList info = emi.getEmpInfo(102);
Iterator it = info.iterator();
while (it.hasNext()) {
emip = (EmployeeInfoPojo) it.next();
System.out.println(emip.getName());
}
}
The output Expected is:
John
Jose
Mark
But what am getting is:
Mark
Mark
Mark
Can anyone find me what's wrong with the code????
I think you need to change the below logic...
while (it.hasNext()) {
lp = (loginPojo) it.next();
emp_info.setName(lp.getName());
System.out.println("Before "+emp_info.getName());
data.add(emp_info);
System.out.println("After "+emp_info.getName());
}
to
while (it.hasNext()) {
lp = (loginPojo) it.next();
emp_info = new EmployeeInfoPojo();//create object here
emp_info.setName(lp.getName());
System.out.println("Before "+emp_info.getName());
data.add(emp_info);
System.out.println("After "+emp_info.getName());
}
Because, as you are adding the same object to the ArrayList, its taking the value you last updated.
Your "emp_info" variable is being created outside the loop, which means that the one inside the loop is always the same instance. When you put that instance into a list, it's still the same instance. (Adding something to a list adds that instance, not a copy.)
Move this line:
EmployeeInfoPojo emp_info = new EmployeeInfoPojo();
immediately after this line:
lp = (loginPojo) it.next();
and you should find that your loop behaves more like you would expect it to.
You just create single object of EmployeeInfoPojo in method getEmployeeInfo. You need to initialize ep_info each time you iterate list.
iterator code should look like this -
while (it.hasNext()) {
lp = (loginPojo) it.next();
emp_info = new EmployeeInfoPojo
emp_info.setName(lp.getName());
System.out.println("Before "+emp_info.getName());
data.add(emp_info);
System.out.println("After "+emp_info.getName());
}
In your previous code you just operate on single object that is why when you change this object old value will override and ArrayList adding same object each time while looping.
Hence only last value is reflected in all objects(single object with three reference).
Briefly, you need to create a new EmployeeInfoPojo object within the while loop. Otherwise all you do is change the properties of a single object over and over and over again.
public ArrayList getEmpInfo(int id) {
ArrayList data = new ArrayList();
loginPojo lp=new loginPojo();
Session session = null;
SessionFactory sessionfactory = new Configuration().configure().buildSessionFactory();
session = sessionfactory.openSession();
String sql_query = "from loginPojo where id!=" + id;
Query query = session.createQuery(sql_query);
List<loginPojo> list = query.list();
Iterator it = list.iterator();
while (it.hasNext()) {
//you need to create new object or else it uses same object reference
EmployeeInfoPojo emp_info = new EmployeeInfoPojo();
lp = (loginPojo) it.next();
emp_info.setName(lp.getName());`enter code here`
System.out.println("Before "+emp_info.getName());
data.add(emp_info);
System.out.println("After "+emp_info.getName());
}
return data;
}

Categories

Resources