Formula for generating numbers based on some sequence

I need java logic for the scenario below:

I need a generalized logic in such a way that when I get 5 it should be converted to 0, for 10 it should be 1 and 15 it should be 2 and so on. Can any help me by providing this logic .

One idea I have is I will can have hashmap with key,value pairs .

Can we have any other logic better than this ?

Upvotes: 0

Views: 66

Answers (2)

Anderson Vieira
Anderson Vieira

Reputation: 9049

If you can use Java 8 you could use map to apply (x / 5) - 1 to each element of your original list.

For example:

public static void main(String... args) {
    List<Integer> fiveMultiples = Arrays.asList(5, 10, 15, 20, 25, 30, 35, 40, 45, 50,
                                                55, 60, 65, 60, 75, 80, 85, 90, 95);
    List<Integer> result = fiveMultiples.stream()
                                        .map((x) -> (x / 5) - 1)
                                        .collect(Collectors.toList());
    System.out.println(result);
}

Output:

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 11, 14, 15, 16, 17, 18]

This is superior to using a HashMap since it is simpler, you don't need to spend memory by storing the values in a table and the cost of applying the formula to a value is about the same it would be to use hashCode().

Upvotes: 1

David SN
David SN

Reputation: 3519

Just apply the formula for your sequence to the given number, in your example it could be:

public static void calculate(int number) {
    return (number / 5) - 1;
}

Upvotes: 2

Related Questions