How to print full Arraylist which is stored in a HashMap - arraylist

I need some assistance to get my assignment working.
Goal is to get a shopping cart which is used by different buyer and everybody can add some article to his shopping cart. My idea is to create an arraylist of all articles I put into the shopping cart and map the created arraylist with the hashmap key, string name of the buyer.
Unfortunatelly If I wanna print out the articles for each buyer, I even get all articles of all buyers. To be honest I'm quite new to this and still unsure if this is the right way to get this working. Before I tried Hasmap I wanted to have dynamic name of my arraylists, means the name of the arraylist of article should be the buyer name.
public class Main {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int amount;
String customerName = "";
System.out.println("Wieviel Benutzer möchten einkaufen?");
amount = Integer.parseInt(sc.nextLine());
for (int i = 0; i < amount; i++) {
System.out.println("Name eingeben:");
customerName = sc.nextLine();
Warenkorb.initialCreation(customerName);}}}
class Warenkorb {
private static ArrayList<Artikel> shoppingCart = new ArrayList<>();
private static HashMap<String, ArrayList<Artikel>> map = new
HashMap<String, ArrayList<Artikel>>();
private static Scanner sc = new Scanner(System.in);
public static void initialCreation(String customerName) {
String currentUser = customerName;
int amountofitem;
System.out.println("How many Arcticle do you want to create");
amountofitem = Integer.parseInt(sc.nextLine());
for (int i = 0; i < amountofitem; i++) {
String artikelName = "";
int price, qty;
System.out.println(">>>Add Article<<<");
System.out.println("Please enter article name");
artikelName = sc.nextLine().trim().toString();
System.out.println("Please enter price");
price = Integer.parseInt(sc.nextLine());
System.out.println("Please enter how many you would like to add -> quantity");
qty = Integer.parseInt(sc.nextLine());
Artikel bla = new Artikel(artikelName, qty, price);
shoppingCart.add(bla);
}
map.put(currentUser, shoppingCart);
for (Map.Entry<String, ArrayList<Artikel>> entry : map.entrySet()) {
System.out.println("Shopping Cart of " + entry.getKey());
for (Artikel item : entry.getValue()) {
System.out.println("Artikel" + " " + item.getItemName() + " " + item.getItemPrice() + "€ " + item.getItemTax() + "%.");
}
}
}
This is what I get if I try to print out each shoppingcart:
Shopping Cart of PEter
Artikel Apfel 3€ 3%.
Artikel Banana 3€ 3%.
Shopping Cart of Chris
Artikel Apfel 3€ 3%.
Artikel Banana 3€ 3%.

The problem is that your shoppingCart and map are defined in static context of the class. Every time you call initialCreation method it deals with the same collections. I'd suggest to make collections non-static and initialCreated method as well.

public class Main {
private static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int amount;
String customerName = "";
System.out.println("Wieviel Benutzer möchten einkaufen?");
amount = Integer.parseInt(sc.nextLine());
for (int i = 0; i < amount; i++) {
System.out.println("Name eingeben:");
customerName = sc.nextLine();
new Warenkorb().initialCreation(customerName);
}
}
}
class Warenkorb {
private ArrayList<String> shoppingCart = new ArrayList<>();
private HashMap<String, ArrayList<String>> map = new HashMap<>();
private Scanner sc = new Scanner(System.in);
public void initialCreation(String customerName) {
// you code
}
}
Something like that.

Related

optaplanner can't get the best solution, and different input orders produce different solutions

I'm trying to make a demo using optaplanner: there are some schemes, each scheme has attribute of gain and cost, and a scheme may conflict with one or more other schemes. The question is to find out a group of schemes which match following constraints:
hard constraint: selected schemea may not conflict with each other in this group
soft constraint: make the difference between total gain and total cost as high as possible
I built following code and try to resolve the question:
#PlanningEntity
#Data
#NoArgsConstructor
public class Scheme {
#PlanningId
private String id;
private int gain;
private int cost;
#PlanningVariable(valueRangeProviderRefs = {"validRange"})
// when valid is ture means this scheme will be selected into the solution group
private Boolean valid;
private Set<String> conflicts = new HashSet<>();
public void addConflict(String id) {
conflicts.add(id);
}
public Scheme(String id, int gain, int cost, String[] conflicts) {
this.id = id;
this.gain = gain;
this.cost = cost;
for (String s : conflicts) {
addConflict(s);
}
}
}
#PlanningSolution
public class SchemeSolution {
private HardSoftScore score;
private List<Scheme> schemeList;
#ProblemFactCollectionProperty
#ValueRangeProvider(id = "validRange")
public List<Boolean> getValidRange() {
return Arrays.asList(Boolean.FALSE, Boolean.TRUE);
}
#PlanningScore
public HardSoftScore getScore() {
return score;
}
public void setScore(HardSoftScore score) {
this.score = score;
}
#PlanningEntityCollectionProperty
public List<Scheme> getSchemeList() {
return schemeList;
}
public void setSchemeList(List<Scheme> schemeList) {
this.schemeList = schemeList;
}
}
And the constraint rule as below:
rule "conflictCheck"
when
Boolean(this==true) from accumulate (
$schs: List() from collect (Scheme(valid==true)),
init(boolean cfl = false;Set cfSet = new HashSet();List ids = new ArrayList()),
action(
for(int i = 0; i < $schs.size(); ++i) {
Scheme sch = (Scheme)$schs.get(i);
cfSet.addAll(sch.getConflicts());
ids.add(sch.getId());
}
for( int i = 0; i < ids.size(); ++i) {
String id = (String)ids.get(i);
if(cfSet.contains(id)) {
cfl = true;
return true;
}
}
),
result(cfl)
)
then
scoreHolder.addHardConstraintMatch(kcontext, -10000);
end
rule "bestGain"
when
$gc : Number() from
accumulate(
Scheme(valid==true, $gain : gain, $cost: cost),
sum($gain - $cost)
)
then
scoreHolder.addSoftConstraintMatch(kcontext, $gc.intValue());
end
Then I constructed three schemes as input of the test. Oddly, I found that optaplanner can't get the best solution, and different input orders produce different solutions.
When I set input as following:
private static List<Scheme> getSchemes() {
List<Scheme> ret = new ArrayList();
ret.add(new Scheme("S1", 5, 2, new String[]{"S3"}));
ret.add(new Scheme("S2", 3, 1, new String[]{"S3"}));
ret.add(new Scheme("S3", 10, 4, new String[]{"S1", "S2"}));
return ret;
}
the output is :
0hard/5soft
Scheme(id=S1, gain=5, cost=2, valid=true, conflicts=[S3])
Scheme(id=S2, gain=3, cost=1, valid=true, conflicts=[S3])
Scheme(id=S3, gain=10, cost=4, valid=false, conflicts=[S1, S2])
And when I set input as following:
private static List<Scheme> getSchemes() {
List<Scheme> ret = new ArrayList();
ret.add(new Scheme("S3", 10, 4, new String[]{"S1", "S2"}));
ret.add(new Scheme("S1", 5, 2, new String[]{"S3"}));
ret.add(new Scheme("S2", 3, 1, new String[]{"S3"}));
return ret;
}
I get the best solution and the output is :
0hard/6soft
Scheme(id=S3, gain=10, cost=4, valid=true, conflicts=[S1, S2])
Scheme(id=S1, gain=5, cost=2, valid=false, conflicts=[S3])
Scheme(id=S2, gain=3, cost=1, valid=false, conflicts=[S3])
Could anyone help me about it?

hadoop mapreduce common friends reducer spillage

I am trying to run the below code, to find the common friends between two persons. The input is as follows
A : B C D
B : A C D E
C : A B D E
D : A B C E
E : B C D
I am not able to get any output in the output file and there is no exception.
Please find my code below,
public class Friend {
public static class Mapperfriend extends Mapper<Object, Text, Text, Text>{
private Text vendor = new Text();
#Override
protected void map(Object key, Text value, Context context) throws IOException, InterruptedException {
StringTokenizer tokenizer = new StringTokenizer(value.toString(), "\n");
String line = null;
String[] lineArray = null;
String[] friendArray = null;
String[] tempArray = null;
while(tokenizer.hasMoreTokens()){
line = tokenizer.nextToken();
lineArray = line.split(":");
friendArray = lineArray[1].split(" ");
tempArray = new String[2];
for(int i = 0; i < friendArray.length; i++){
tempArray[0] = friendArray[i];
tempArray[1] = lineArray[0];
Arrays.sort(tempArray);
context.write(new Text(tempArray[0] + " " + tempArray[1]), new Text(lineArray[1]));
}
}
}}
public static class ReducerFriend extends Reducer<Text,Text,Text,Text>{
#Override
protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
Text[] texts = new Text[2];
int index = 0;
for(Text val: values)
{
texts[index++] = new Text(val);
}
String[] list1 = texts[0].toString().split(" ");
String[] list2 = texts[1].toString().split(" ");
List<String> list = new LinkedList<String>();
for(String friend1 : list1){
for(String friend2 : list2){
if(friend1.equals(friend2)){
list.add(friend1);
}
}
}
StringBuffer sb = new StringBuffer();
for(int i = 0; i < list.size(); i++){
sb.append(list.get(i));
if(i != list.size() - 1)
sb.append(" ");
}
context.write(key, new Text(sb.toString()));
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws Exception {
// TODO code application logic here
Configuration conf = new Configuration();
Job job = Job.getInstance(conf, "Friends");
job.setJarByClass(Friend.class);
job.setMapperClass(Mapperfriend.class);
job.setReducerClass(ReducerFriend.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(Text.class);
FileInputFormat.addInputPath(job, new Path(args[0]));
FileOutputFormat.setOutputPath(job, new Path(args[1]));
System.exit(job.waitForCompletion(true) ? 0 : 1);
}
}
The mapper class emitted the entire key from first. Instead of picking up the array. When removed that it works fine.

Arraylist not displaying the right output

My main class code
{
ArrayList<Item> items = new ArrayList<Item>();
Scanner file = new Scanner(kk.class.getResourceAsStream("product.txt"));
while (file.hasNextLine()) {
String[] sp = file.nextLine().split(",");
// extract item number, description, price and type
itemNum = Integer.parseInt(sp[0]);
des = sp[1];
price = Integer.parseInt(sp[2]);
Item objt = new Item(itemNum, des, price); // Creating a new object
items.add(objt); // Adding it to the list
}
System.out.println(items);
}
output I am getting
[dada.Item#4a5d4a62, dada.Item#32be8e12, dada.Item#7c6159c4, dada.Item#5b4c92a7, dada.Item#3040c5,
My item class code
private int itemNum = 0;
private String des = "";
private int price = 0;
public Item(int i, String d, int p) {
itemNum = i;
des = d;
price = p;
}
You're printing the Item reference's address instead of the fields inside your Item object. You have print the fields inside each Item object by looping through them.
Replace this line
System.out.println(items);
with
for(Item i : items)
{
System.out.println(i.getItemNum()+" "+i.getDes()+" "+i.getPrice());
}
Change the class so that you could access your private fields
private int itemNum = 0;
private String des = "";
private int price = 0;
public Item(int i, String d, int p) {
itemNum = i;
des = d;
price = p;
}
public void setItemNum(int itemNum) {
this.itemNum = itemNum;
}
public int getItemNum() {
return itemNum;
}
public void setDes(String des) {
this.des = des;
}
public String getDes() {
return des;
}
public void setPrice(int price) {
this.price = price;
}
public int getPrice() {
return price;
}

Get results with exact match

I want to do a query like that : "banana apple cherry" on a "fruit" field.
All the fruits in the desserts needs to be in the query, but not all the fruits in the query needs to be in the desserts..
Here's an example..
NAME FRUIT
Dessert1 banana apple OK (we got banana and apple in the query)
Dessert2 cherry apple banana OK(the order doesn't matter)
Dessert3 cherry apple banana melon NO (melon is missing in the query)
public class ArrayStringFieldBridge implements TwoWayFieldBridge{
#Override
public Object get(String name, Document document) {
IndexableField[] fields = document.getFields(name);
String[] values = new String[fields.length];
for (int i=0; i<fields.length; i++) {
values[i] = fields[i].stringValue();
}
return values;
}
#Override
public String objectToString(Object value) {
return StringUtils.join((String[])value, " ");
}
#Override
public void set(String name, Object value, Document document, LuceneOptions luceneOptions) {
String newString = StringUtils.join((String[])value, " ");
Field field = new Field(name, newString, luceneOptions.getStore(), luceneOptions.getIndex(), luceneOptions.getTermVector());
field.setBoost(luceneOptions.getBoost());
document.add(field);
}
}
#Indexed
#AnalyzerDef(name = "customanalyzer",
tokenizer = #TokenizerDef(factory = StandardTokenizerFactory.class))
public class Dessert {
#Analyzer(definition="customanalyzer")
#Field(name = "equipment", index=Index.YES, analyze = Analyze.YES, store=Store.YES)
#FieldBridge(impl=ArrayStringFieldBridge.class)
public String[] fruits = new String[]{};
}
Even if you are not using hibernate-search, every suggestions about the theory to handle that would be great... Thank you
Step 1 : Fire lucene query "fruit:banana OR fruit:apple OR fruit:cherry"
Step 2 : Gather all matched dessert documents
Step 3 : Post process your match dessert document with query
convert match document to array of terms matchDocArr : {banana, apple}
convert query terms to array - queryArr : {banana, apple, cherry}
iterate over matchDocArr and make sure each term of matchDocArr is found in queryArr by array, if NOT (melon use case) knockout this matched document
Here is an example function which needs to be called for every matched doc
public static boolean isDocInterested(String query, String matchDoc)
{
List<String> matchDocArr = new ArrayList<String>();
matchDocArr = Arrays.asList(matchDoc.split(" "));
List<String> queryArr = new ArrayList<String>();
queryArr = Arrays.asList(query.split(" "));
int matchCounter = 0;
for(int i=0; i<matchDocArr.size(); i++)
{
if (queryArr.contains(matchDocArr.get(i)))
matchCounter++;
}
if (matchCounter == matchDocArr.size())
return true;
return false;
}
if function returns TRUE we are interested in doc/dessert, if it returns FALSE ignore this doc/dessert.
of course this function can be written in many different ways but I think you get the point.

How do you input data into a constructor from scanner?

I am trying to take a constructor(string, string, double) and set the value in it with a scanner input. any help is appreciated. The code is list below.
My programs can assign the values that i put in, but I want to be able to assign them from the keyboard and I would like to use only one constructor method to accomplish this. Thanks
I have it broken up into two classes:
import java.util.Scanner;
public class EmployeeTest
{
public static void main(String [] args)
{
Scanner input = new Scanner(System.in);
Employee employee1 = new Employee("james", "ry", 3200);
Employee employee2 = new Employee("jim" , "bob" , 2500.56 );
System.out.println("What is employyee 1's first name? ");
employee1.setFname(input.nextLine());
}
}
class Employee
{
private String fname;
private String lname;
private double pay;
public Employee(String fname, String lname, double pay)
{
this.setFname(fname);
this.lname = lname;
this.pay = pay;
System.out.println("Employee " + fname +" "+ lname + " makes $" +
+ pay + " this month and with a 10% raise, their new pay is $" + (pay * .10 + pay));
}
void setfname(String fn)
{
setFname(fn);
}
void setlname(String ln)
{
lname = ln;
}
void setpay (double sal)
{
pay = sal;
}
String getfname()
{
return getFname();
}
String getlname()
{
return lname;
}
double getpay()
{
if (pay < 0.00)
{
return pay = 0.0;
}
return pay;
}
public String getFname() {
return fname;
}
public void setFname(String fname)
{
this.fname = fname;
}
}
You can modify you EmployeeTest class something like
class EmployeeTest {
public static void main (String...arg) {
Scanner s = new Scanner(System.in);
String[] elements = null;
while (s.hasNextLine()) {
elements = s.nextLine().split("\\s+");
//To make sure that we have all the three values
//using which we want to construct the object
if (elements.length == 3) {
//call to the method which creates the object needed
//createObject(elements[0], elements[1], Double.parseDouble(elements[2]))
//or, directly use these values to instantiate Employee object
} else {
System.out.println("Wrong values passed");
break;
}
}
s.close();
}
}