0

I have the following textfile contains the information that will be added to the treemap.

1 apple
1 orange
3 pear
3 pineapple
4 dragonfruit

my code:

public class Treemap {

    private List<String> fList = new ArrayList<String>();
    private TreeMap<Integer, List<String>> tMap = new TreeMap<Integer, List<String>>();

    public static void main(String[] args) {
        Treemap tm = new Treemap();
        String file = "";
        if (args.length == 1) {
            file = args[0];

            try {
                tm.Read(file);
            } catch (IOException ex) {
                System.out.println("Error");
            }

        } else {
            System.out.println("Usage: java treemap 'Filename'");
            System.exit(1);
        }
    }
    public void Read(String file) throws IOException {
        //Scanner in = null;
        BufferedReader in = null;
        InputStream fis;

        try {
            fis = new FileInputStream(file);
            in = new BufferedReader(new InputStreamReader(fis));
            String line = null;
            while ((line = in.readLine()) != null) {

                String[] file_Array = line.split(" ", 2);

                if (file_Array[0].equalsIgnoreCase("1")) {
                    Add(Integer.parseInt(file_Array[0]), file_Array[1]);
                    Display(1);
                } else if (file_Array[0].equalsIgnoreCase("3")) {
                    Add(Integer.parseInt(file_Array[0]), file_Array[1]);
                    Display(3);
                } else if (file_Array[0].equalsIgnoreCase("4")) {
                    Add(Integer.parseInt(file_Array[0]), file_Array[1]);
                    Display(4);
                }
            }
        } catch (IOException ex) {
            System.out.println("Input file " + file + " not found");
            System.exit(1);
        } finally {

            in.close();

        }
    }
    public void Add(int item, String fruit) {
        if (tMap.containsKey(item) == false) {
            tMap.put(item, fList);
            fList.add(fruit);
            System.out.println("Fruits added " + item);
        } else {
            System.out.println("not exist");
        }
    }
    public void Display(int item) {

        if (tMap.containsKey(item)) {
            System.out.print("Number " + item + ":" + "\n");
             System.out.print(fList);
            System.out.print("\n");
        } else {
            System.out.print(item + " WAS NOT FOUND"+ "\n");
        }

    }
}

ideal output

Number 1:
[apple, orange]

Number 3:
[pear, pineapple]

Number 4:
[dragonfruit]

currently i only able to output this

Fruits added 1
Number 1:
[apple]
not exist
Number 1:
[apple]
Fruits added 3
Number 3:
[apple, pear]
not exist
Number 3:
[apple, pear]
Fruits added 4
Number 4:
[apple, pear, dragonfruit]

How should I display the item following by the list of fruit added to that number?

2
  • Don't call Display() method everytime you add something to the map. Call it at the end of the while loop. And please follow proper Java naming conventions. Commented Oct 23, 2013 at 5:25
  • Note that in.close(); in finally won't be executed if the catch block is executed, because there you are doing a System.exit(1);. Bad idea. Commented Oct 23, 2013 at 5:43

4 Answers 4

3

Try this code. Its working. By the way you should improve this code. The code is not optimised.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class Treemap {

private List<String> fList = new ArrayList<String>();
private TreeMap<Integer, List<String>> tMap = new TreeMap<Integer, List<String>>();

public static void main(String[] args) {
    Treemap tm = new Treemap();
    String file = "";
    if (args.length == 1) {
        file = args[0];

        try {
            tm.Read(file);
        } catch (IOException ex) {
            System.out.println("Error");
        }

    } else {
        System.out.println("Usage: java treemap 'Filename'");
        System.exit(1);
    }
}
public void Read(String file) throws IOException {
    //Scanner in = null;
    BufferedReader in = null;
    InputStream fis;

    try {
        fis = new FileInputStream(file);
        in = new BufferedReader(new InputStreamReader(fis));
        String line = null;
        while ((line = in.readLine()) != null) {

            String[] file_Array = line.split(" ", 2);

            if (file_Array[0].equalsIgnoreCase("1")) {
                Add(Integer.parseInt(file_Array[0]), file_Array[1]);
               // Display(1);
            } else if (file_Array[0].equalsIgnoreCase("3")) {
                Add(Integer.parseInt(file_Array[0]), file_Array[1]);
               // Display(3);
            } else if (file_Array[0].equalsIgnoreCase("4")) {
                Add(Integer.parseInt(file_Array[0]), file_Array[1]);
               // Display(4);
            }
        }
    } catch (IOException ex) {
        System.out.println("Input file " + file + " not found");
        System.exit(1);
    } finally {
        for(int i: tMap.keySet())
            Display(i);
        in.close();

    }
}
public void Add(int item, String fruit) {
    if (tMap.containsKey(item) == false) {
        fList = new ArrayList<>();
        fList.add(fruit);
        tMap.put(item, fList);

       // System.out.println("Fruits added " + item);
    } else {
        tMap.get(item).add(fruit);
       // System.out.println("not exist");
    }
}
public void Display(int item) {

    if (tMap.containsKey(item)) {
        System.out.print("Number " + item + ":" + "\n");
         System.out.print(tMap.get(item));
        System.out.print("\n");
    } else {
        System.out.print(item + " WAS NOT FOUND"+ "\n");
    }

}

}

Sign up to request clarification or add additional context in comments.

Comments

1

Here is your READ , ADD ad DISPLAY method,

public void Read(String file) throws IOException {
        BufferedReader in = null;
        InputStream fis;

        try {
            fis = new FileInputStream(file);
            in = new BufferedReader(new InputStreamReader(fis));
            String line = null;
            while ((line = in.readLine()) != null) {
                String[] file_Array = line.split(" ", 2);
                Add(Integer.parseInt(file_Array[0]),file_Array[1]);
            }
            Display(-1); // -1 for displaying all
        } catch (IOException ex) {
            System.out.println("Input file " + file + " not found");
            System.exit(1);
        } finally {
            in.close();
        }
    }

    public void Add(int item, String fruit) {
        if (tMap.containsKey(item)) {
            fList = tMap.get(item);
        } else {
            fList = new ArrayList<String>();
        }
        fList.add(fruit);
        tMap.put(item, fList);
    }

    public void Display(int key) {
    if(key == -1){
        for (Map.Entry<Integer, List<String>> entry : tMap.entrySet()) {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }
    }else{
        System.out.println(key);
        System.out.println(tMap.get(key));
    }

}

1 Comment

Display() method display everything out what if I only want to display item 1? 1 [apple, orange]
1

You make unnecessary complicated your code. Try with simple code.

public class Treemap {

    public static void main(String[] args) throws FileNotFoundException {
        Scanner sc = new Scanner(new File("file.txt"));
        Map<Integer, List<String>> tMap = new TreeMap<>();

        while (sc.hasNextLine()) {
            String line = sc.nextLine();
            String[] values=line.split(" ");
            List<String> fList;
            Integer key=Integer.valueOf(values[0]);
            if(tMap.containsKey(key)){//Key already inserted
                fList=tMap.get(key); //Get existing List of key
                fList.add(values[1]);
            }
            else{
                fList = new ArrayList<String>();
                fList.add(values[1]);
                tMap.put(key, fList);
            }
        }
        for (Map.Entry<Integer, List<String>> entry : tMap.entrySet()) {
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }

    }
}

Output:

1
[apple, orange]
3
[pear, pineapple]
4
[dragonfruit]

1 Comment

You're unnecessary creating a new ArrayList on each iteration. Move that to the else block. And inside the if block, just do - tMap.get(key).add(values[1]);.
1

Change some code for the method Add(), which is incorrect in your code.

What if the Map contains the key?

Following code is modified based on your code, hope this can help you some.

public void Add(int item, String fruit) {
    if (tMap.containsKey(item)==false) {
        fList.clear();
        fList.add(fruit);
        tMap.put(item, fList);

        System.out.println("Fruits added " + item);
    } else {
        tMap.get(item).add(fruit);
    }
}

2 Comments

tMap.containsKey(item)==false? Please don't do that. Boolean comparison is evil, and should be avoided. Just do !tMap.containsKey(item).
oh, i never though of that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.