0

I am trying to match two string using following lines

int row = 1;
String index = row + ",(.*)";
String R = "1,2";
Object result = index.equals(R);

The result is false while I want it to be true.I cannot use other method link .matches() and not even the pattern object for the index as i want it to integrate with other method which uses Hashmap .

In the map keys (String) will have indexes link (1,2) , (1,3) , (2,3), ... I want to search them from the first number i.e 1 , 2 and so on.

Thanks in advance.

mohammed ahmed
  • 195
  • 1
  • 10
  • 3
    `String#equals` doesn't invoke a regex engine, it does an exact comparison. If you need regex functionality, then you'll have to use `String#matches`, or use a `Pattern`. – Tim Biegeleisen Sep 13 '18 at 15:26
  • `The result is false while I want it to be true.` — you won't get this expression to return `true` in Java ;) – Alex Shesterov Sep 13 '18 at 15:27
  • 1
    Please add an example of how you use it with `HashMap`. You can't change `String.equals()` implementation. – Karol Dowbecki Sep 13 '18 at 15:28
  • 1
    Why are you declaring result as Object when it is a boolean? – m0skit0 Sep 13 '18 at 15:30
  • https://stackoverflow.com/questions/1986031/how-to-use-pattern-matcher-in-java might prove useful, even if it is referencing HTML regex parsing (which is a bad idea) - "matches" only works if it completely matches the pattern. You want partial matching - you'll need a Matcher object for that level of detail. – Jeutnarg Sep 13 '18 at 15:50

2 Answers2

3

You can't change String.equals() behaviour. If you insist to get true use:

Object result = !index.equals(R);
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
0

It would be

boolean result = R.matches(index);

or

boolean result = R.startsWith(row + ",");

Now a HashMap has no sorted keys, however there is a Map that also is a SortedMap, namely TreeMap:

Instead of

Map<String, T> map = new HashMap<>();

do

SortedMap<String, T> map = new TreeMap<>();

As "1," < "12," given that ',' < '0' the standard String comparison suffices.

Then receiving the sub-map of a row is possible:

String firstKey = row + ",";
String lastKey = row + "/"; // As '/' > ','

SortedMap submap = map.subMap(firstKey, lastKey);

This submap is backed by the original map, that is, changing it will change the map.

It should be said, that the keys seem a bit artificial, maybe row + another field in a RowKey class, or Map<Integer, Map<String, T>> (row map first) would make more sense.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138