Home > Software design >  Why Stream collect toMap function givers an error?
Why Stream collect toMap function givers an error?

Time:07-18

Hoisting class:

public class Hosting {
    private int id;
    private String name;
    private long websites;

    public Hosting(int id, String name, long websites) {
        id = id;
        this.name = name;
        this.websites = websites;
    }
    public int getId(int id) {
        return id;
    }
    public String getName(String name) {
        return name;
    }
}

I am trying to run

public class TestSortCollect{
    public static void main(String[] args) {
        ArrayList<Hosting> list = new ArrayList<>();
        list.add(new Hosting(1, "liquidweb.com", 80000));
        list.add(new Hosting(2, "linode.com", 90000));
        list.add(new Hosting(3, "digitalocean.com", 120000));
        list.add(new Hosting(4, "aws.amazon.com", 200000));
        list.add(new Hosting(5, "mkyong.com", 1));
        
        HashMap<Integer, String> result1 = list.stream().collect(
                Collectors.toMap(Hosting::getId, Hosting::getName));

        System.out.println("Result 1 : "   result1);

    }
}

It gives an error: The method toMap(Function<? super T,? extends K>, Function<? super T,? extends U>) in the type Collectors is not applicable for the arguments (Hosting::getId, Hosting::getName). How can I print result1 value?

CodePudding user response:

you get the Exception in thread "main" java.lang.IllegalStateException: Duplicate key 0 (attempted merging values liquidweb.com and linode.com) because you the below in Hosting class.

public Hosting(int id, String name, long websites) {
        id = id;

this should be

public Hosting(int id, String name, long websites) {
        this.id = id;

CodePudding user response:

You misspelled Hosting class' content.

  1. In the constructor you assigned to parameter id its same value (id = id).
  2. getId() and getName() return the same value given as parameter.

I guess you need to review the use of this keyword in jls. The rest is ok. You just need to downcast .collect()'s return to (HashMap<Integer, String>) to fit result1.

static class Hosting {
    private int id;
    private String name;
    private long websites;

    public Hosting(int id, String name, long websites) {
            this.id = id;
            this.name = name;
            this.websites = websites;
        }
        public int getId() {
            return id;
        }
        public String getName() {
            return name;
        }
}
  • Related