Getting data from a given String separated by (,,-) in java - java

I am having a String like this "5006,3030,8080-8083".
I want each element separately from the String:
5006
3030
8080
8081
8082
8083
Here's my code:
int i=0,j=0;
String delim = "[,]";
String hyphon = "[-]";
String example = "5006,3030,8080-8083";
String p[] = example.split(delim);
int len = p.length;
for(i=0;i<len;i++) {
String ps[]=p[i].split(hyphon);
if(ps.length>1) {
int start = Integer.parseInt(ps[0]);
int finish = Integer.parseInt(ps[1]);
int diff = finish-start+1;
for(j=0;j<diff;j++) {
System.out.println(start+j);
}
} else if(ps.length==1) {
System.out.println(ps[0]);
}
}
Is there any better solution or any class that simplifies my code?
I also want the numbers in a ascending order.

Try this code :
public static void main(String[] args) {
String input = "5006,3030,8080-8083";
List<Integer> list = new ArrayList<Integer>();
String[] numbers = input.split(",");
for (String s : numbers) {
if (s.contains("-")) {
String[] range = s.split("-");
int from = Integer.parseInt(range[0]);
int to = Integer.parseInt(range[1]);
for (int i = from; i <= to; i++) {
list.add(i);
}
}
else {
list.add(Integer.parseInt(s));
}
}
System.out.println("in asc order");
Collections.sort(list);
System.out.println(list.toString());
System.out.println("in desc order");
Collections.reverse(list);
System.out.println(list.toString());
}
My output :
in asc order
[3030, 5006, 8080, 8081, 8082, 8083]
in desc order
[8083, 8082, 8081, 8080, 5006, 3030]

I also want the numbers in a ascending order.
This adds an unexpected twist to your whole program, because once you realize that printing-as-you-go no longer works, you need to start almost from scratch.
The first thing to do is picking an appropriate representation. It appears that you represent ranges of integers, so start by defining a class for them:
class IntRange : Comparable<IntRange> {
private int low, high;
public int getLow() {return low;}
public int getHigh() {return high;}
public IntRange(int low, int high) {
// Add range check to see if low <= high
this.low = low; this.high = high;
}
public IntRange(int point) {low = high = point;}
#Override
public void print() {
for (int i = low ; i <= high ; i++) {
System.out.println(i);
}
}
#Override
public int compareTo(IntRange other) {
...
}
}
Now you can use your code to split on [,], then split on [-], construct IntRange, and put it into an ArrayList<IntRange>. After that you can use sort() method to sort the ranges, and print them in the desired order.
But wait, there is more to your problem than meets the eye. Think what would happen for input like this:
1,5,3-7,6
Where should 5 and 6 be printed? It is not good to print it before or after 3-7, so the trick is to remove points inside ranges.
But even that's not all: what do you do about this input?
1-5,3-7
You should print numbers 1 through 7, inclusive, but this would require merging two ranges. There is a good data structure for doing this efficiently. It is called a range tree. If your input is expected to be large, you should consider using range tree representation.

You are good to go; you can minimize the counter variables using enhanced for loop and while loop.
String example = "5006,3030,8080-8083";
String[] parts=example.split(",")
ArrayList<Integer> numbers = new ArrayList<Integer>();
for(String part: parts)
{
if(part.contains("-"))
{
String subParts[]=part.split("-");
int start = Integer.parseInt(subParts[0]);
int finish = Integer.parseInt(subParts[1]);
while(start <= finish)
{
numbers.add(start);
System.out.println(start++);
}
}
else {
System.out.println(part);
numbers.add(Integer.parseInt(part));
}
}
Integer[] sortedNumbers = new Integer[numbers.size()];
sortedNumbers = Arrays.sort(numbers.toArray(sortedNumbers));
Update (from comment):
Numbers are sorted now.

Try this
String str = "5006,3030,8080-8083";
String[] array = str.split(",");
String ans = "";
for(int i = 0; i < array.length; i++){
if(array[i].contains("-")){
String[] array2 = array[i].split("-");
int start = Integer.parseInt(array2[0]);
int end = Integer.parseInt(array2[array2.length - 1]);
for(int j = start; j <= end; j++){
ans = ans + j + ",";
}
}
else{
ans = ans + array[i] + ",";
}
}
System.out.print(ans);

This code assumes all integers are positive.
public static void main(String[] args) {
String testValue="5006,3030,8080-8083";
Integer[]result=parseElements(testValue);
for (Integer i:result){
System.out.println(i);
}
}
/**
* NumberList is a string of comma-separated elements that are either integers, or a range of integers of the form a-b.
* #param numberList
* #return all the integers in the list, and in ranges in the list, in a sorted list
*/
private static Integer[] parseElements(String integerList) {
ArrayList<Integer> integers=new ArrayList<Integer>();
String[] csvs=integerList.split(",");
for(String csv : csvs){
if(csv.contains("-")){
String[] range=csv.split("-");
Integer left=Integer.decode(range[0]);
Integer right=Integer.decode(range[1]);
for(Integer i=left;i<=right;i++){
integers.add(i);
}
} else {
integers.add(Integer.decode(csv));
}
}
Collections.sort(integers);
return integers.toArray(new Integer[0]);
}

Using Guava's functional idioms you can achive this declaratively, avoiding the verbose, imperative for-loops. First declare a tokenizing function which converts each token in the comma-delimited string into an Iterable<Integer>:
private static final Function<String, Iterable<Integer>> TOKENIZER =
new Function<String, Iterable<Integer>>() {
/**
* Converts each token (e.g. "5006" or "8060-8083") in the input string
* into an Iterable<Integer>; either a ContiguousSet or a List with a
* single element
*/
#Override
public Iterable<Integer> apply(String token) {
if (token.contains("-")) {
String[] range = token.trim().split("-");
return ContiguousSet.create(
Range.closed(Integer.parseInt(range[0]),
Integer.parseInt(range[1])),
DiscreteDomain.integers());
} else {
return Arrays.asList(Integer.parseInt(token.trim()));
}
}
};
then apply the function to the input:
String input = "5006,3030,8080-8083";
Iterable<String> tokens = Splitter.on(',').trimResults().split(input);
SortedSet<Integer> numbers = Sets.newTreeSet();
Iterables.addAll(numbers,
// concat flattens the Iterable<Iterable<Integer>>
// into an Iterable<Integer>
Iterables.concat(Iterables.transform(tokens, TOKENIZER)));
As all of the logic is basically coded into the Function, the client code only needs to tokenize the string into an Iterable<String> (with Splitter), apply the Function through Iterables.transform, flatten the result of the transformation using Iterables.concat and finally add the resulting Iterable<Integer> into a SortedSet<Integer> which keeps the numbers in ascending order.

with java 8 stream api :
public static void main(String[] args) {
String s = "5006,3030,8080-8083";
Arrays.stream(s.split(","))
.flatMap(el -> el.contains("-") ? rangeToStream(el) : Stream.of(Integer.valueOf(el)))
.sorted()
.forEachOrdered(e -> System.out.println(e));
}
private static Stream<? extends Integer> rangeToStream(String el) {
AtomicInteger[] bounds = Arrays.stream(el.split("-")).map(e -> new AtomicInteger(Integer.parseInt(e))).toArray(size -> new AtomicInteger[2]);
return Arrays.stream(new Integer[bounds[1].get() - bounds[0].get() + 1]).map(e -> bounds[0].getAndIncrement());
}

U can code something like this -
String s="5006,3030,8080-8083";
String s2[]=s.split(",");
List<Integer> li= new ArrayList<Integer>();
List<Integer> numbers= new ArrayList<Integer>();
for(int i=0;i<s2.length;i++){
if(s2[i].contains("-")){
li.add(i);
}
else{
numbers.add(Integer.parseInt(s2[i]));
}
}
for(Integer i:li){
String str=s2[i];
String strArr[]=str.split("-");
for(int j=Integer.parseInt(strArr[0]);j<=Integer.parseInt(strArr[1]);j++){
numbers.add(j);
}
}
Collections.sort(numbers);
for(Integer k:numbers){
System.out.println(k);
}

public static void main(String[] args)
{
String example = "5006,3030,8080-8083";
String[] splitString = example.split(",");
List<Integer> soretedNumbers = new ArrayList<>();
for(String str : splitString)
{
String[] split2 = str.split("-");
if(split2.length == 1)
{
soretedNumbers.add(Integer.parseInt(str));
}
else
{
int num1 = Integer.parseInt(split2[0]);
int num2 = Integer.parseInt(split2[1]);
for(int i = num1;i <= num2; i++)
{
soretedNumbers.add(i);
}
}
}
Collections.sort(soretedNumbers);
for(int i : soretedNumbers)
{
System.out.println(i);
}
}

Related

Array.sort not sorting all element [duplicate]

I have String[] array like
{"3","2","4","10","11","6","5","8","9","7"}
I want to sort it in numerical order, not in alphabetical order.
If I use
Arrays.sort(myarray);
I obtain
{"10","11","2","3","4","5","6","7","8","9"}
instead of
{"2","3","4","5","6","7","8","9","10","11"}
Try a custom Comparator, like this:
Arrays.sort(myarray, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
}
});
Hope you like it!
I think by far the easiest and most efficient way it to convert the Strings to ints:
int[] myIntArray = new int[myarray.length];
for (int i = 0; i < myarray.length; i++) {
myIntArray[i] = Integer.parseInt(myarray[i]);
}
And then sort the integer array. If you really need to, you can always convert back afterwards:
for (int i = 0; i < myIntArray.length; i++) {
myarray[i] = "" + myIntArray[i];
}
An alternative method would be to use the Comparator interface to dictate exactly how elements are compared, but that would probably amount to converting each String value to an int anyway - making the above approach much more efficient.
I found this article about sorting strings by numeric sorting also for strings that may or may not contain numbers:
The Alphanum Algorithm
There is a Java implementation example linked from the article.
With that class you should be able to sort your arrays numerically like this:
Arrays.sort(myarray, new AlphanumComparator());
U can use sol-1 if it contains only numbers in string format.
Solution-1: -
String []arr = {"3","2","4","10","11","6","5","8","9","7"};
Set<Integer> set = new TreeSet<Integer>();
Arrays.sort(arr);
for(String s:arr){
System.out.print(s+" ");
set.add(Integer.parseInt(s));
}
System.out.println(set);
Integer i = new Integer("4f");
System.out.println(i);
Solution-2:-
String []arr = {"3","2","4","10","11","6","5","8","9","7","jgj","ek"};
Set<Integer> intSet = new TreeSet<Integer>();
Set<String> strSet = new TreeSet<String>();
Arrays.sort(arr);
for(String s:arr){
try {
int i = Integer.parseInt(s);
intSet.add(i);
} catch (NumberFormatException e) {
strSet.add(s);
}
}
List<String> result = new ArrayList<String>();
for(int val:intSet){
result.add(val+"");
}
result.addAll(strSet);
System.out.println(result);
}
Solution-3:-
Write one CustomComparator class and pass it to the sort() method.
public class CustomComparator implements Comparator<String>{
#Override
public int compare(String s1, String s2) {
Integer i1=null;
Integer i2=null;
try {
i1 = Integer.parseInt(s1);
} catch (NumberFormatException e) {
}
try {
i2 = Integer.parseInt(s2);
} catch (NumberFormatException e) {
}
if(i1!=null && i2!=null){
return i1.compareTo(i2);
}else{
return s1.compareTo(s2);
}
}
}
public static void main(){
String []arr = {"3","2","4","10","11","6","5","8","9","7","jgj","ek"};
Arrays.sort(arr, new CustomComparator());
for(String s:arr){
System.out.print(s+" ");
}
}
If all elements if your String array represent numbers, and if the numbers are always positive, then there is a simple way to sort numerically without a limit to the value of the number.
This is based on the fact that a number with a larger number of digits is, in that case, always higher than a number with a smaller number of digits.
You first compare the number of digits, and then (only if the number of digits is the same) you compare the value alphabetically:
Arrays.sort(array,
Comparator.comparing(String::length).thenComparing(Function.identity()));
in jdk8, you can write this code with lambda.
List<String> list = Arrays.asList("3", "2", "4", "10", "11", "6", "5", "8", "9", "7");
list.sort(Comparator.comparingInt(Integer::valueOf));
list.forEach(System.out::println);
especially such as input
String[]{"3.b", "2.c", "4.d", "10.u", "11.a", "6.p", "5.i", "8.t", "9.e", "7.i"}
you can use string.subString to chose which value is you really want to sort.
like
files.sort(Comparator.comparingInt(a -> Integer.valueOf(a.substring(0, a.indexOf(".")))));
Your desired output contains the numerical order of corresponding integers of your strings. So simply you cannot avoid conversion of strings to integers. As an alternative comparator to vikingsteve's you can use this:
Arrays.sort(array, new Comparator<String>() {
#Override
public int compare(String str1, String str2) {
return Integer.parseInt(str1) - Integer.parseInt(str2);
}
});
public class test1 {
public static void main(String[] args)
{
String[] str = {"3","2","4","10","11","6","5","8","9","7"};
int[] a = new int[str.length];
for(int i=0;i<a.length;i++)
{
a[i]=Integer.parseInt(str[i]);
}
Arrays.sort(a);
for(int i=0;i<a.length;i++)
{
str[i]=String.valueOf(a[i]);
}
}
}
This is the best solution I could come with, we can't convert to integer when the string is huge, this method sort an array of strings
public static void sortListOfStringsAsNumbers(List<String> unsorted) {
String min = "";
for (int i = 0; i < unsorted.size(); i++){
min = unsorted.get(i);
int indexMin = i;
for (int j = i + 1; j < unsorted.size(); j++){
if (unsorted.get(j).length() < min.length()){
min = unsorted.get(j);
indexMin = j;
}else if (unsorted.get(j).length() == min.length()){
for (int x = 0; x < unsorted.get(j).length(); x ++){
if (unsorted.get(j).charAt(x) < min.charAt(x)){
min = unsorted.get(j);
indexMin = j;
}else if (unsorted.get(j).charAt(x) > min.charAt(x)){
break;
}
}
}
}
if (indexMin != i){
String temp = unsorted.get(i);
unsorted.set(i, min);
unsorted.set(indexMin, temp);
}
}
}
All the solutions are for only integer numbers. what if the array contains floating numbers as well?
Here is the best solution which allows you to sort any type of value in the string.
import java.math.BigDecimal;
import java.util.*;
class Sort
{
public static void main(String...arg)
{
String s[]={"-100","50","0","56.6","90","0.12",".12","02.34","000.000"};
System.out.println("\n"+Arrays.toString(s)); //print before sorting
Arrays.sort(s, new Comparator<String>() {
public int compare(String a1, String a2) {
BigDecimal a = new BigDecimal(a1);
BigDecimal b = new BigDecimal(a2);
return a.compareTo(b);
}
});
System.out.println("\n"+Arrays.toString(s)); //print after sorting
}
}

Split a String into number of Characters desired by the user

I want to split a String into n number of characters.
Consider input to be "Example-for-my-Question". Now if I want to split into n=3 characters, output should be "Exa, mpl, e-f, or-, my-, Que, sti, on" and suppose n=4, output should be "Exam, ple-, for-, my-Q, uest, ion" How can you modify the program below without using POSIX.
import java.util.Scanner;
public class SplitString {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a String; ");
String inputString = in.nextLine();
System.out.println("How many characters do you want to split into ?");
int n = in.nextInt();
String[] array = inputString.split(" ", n);
System.out.println("Number of words: " + array.length);
for (String arr : array)
System.out.println(arr);
}
}
The simple way to do this is to use String.substring(...) repeatedly to trim N characters off the front of your string ... in a loop.
But if you really want to do this using String.split(...), then I think that the separator regex needs to be a positive look-behind that matches N characters. (It is obscure, and inefficient ... but if regexes are your universal tool ...)
You can use substring for this task.
String sp="StackOverFlow";
int NoOfChars=3;
for(int i=0;i<sp.length();i+=NoOfChars)
{
if(i+NoOfChars<=sp.length())
System.out.println(sp.substring(i,i+NoOfChars));
//Instead add in String ArrayList
else
System.out.println(sp.substring(i));
}
OUTPUT
Sta
ckO
ver
Flo
w
NOTE:Better to use trim() to remove leading or trailing spces
This works for me. In addition to splitting into known lengths, it checks for a null or "too small of a" source string, etc. If a null string is supplied, then a null is returned. If the source string is smaller than the requested split length, then the source string is simply returned.
public static void main (String[] args) throws java.lang.Exception
{
// Three test cases...
String pieces[] = SplitString("Example-for-my-Question", 3);
//String pieces[] = SplitString("Ex", 3);
//String pieces[] = SplitString(null, 3);
if (null != pieces)
{
for (int i = 0; i < pieces.length; i++)
{
System.out.println(pieces[i]);
}
}
}
private static String[] SplitString(String source, int size)
{
String result[] = null;
if (null != source && source.length() > size)
{
int numberOfElements = source.length() / size;
int modulo = source.length() % size;
if (modulo > 0)
{
numberOfElements++;
}
result = new String[numberOfElements];
for (int i = 0; i < numberOfElements; i++)
{
if (numberOfElements - 1 != i)
{
result[i] = source.substring(i * size, (i * size) + size);
}
else
{
result[numberOfElements - 1] = source.substring(i * size, (i * size) + modulo);
}
}
}
else if (null != source)
{
result = new String[1];
result[0] = source;
}
return result;
}
Please try the following program, but here you have to give input to "N" inside the program itself
class Main {
public static void main(String[] args) {
int N = 5;
String text = "aaaaabbbbbccccceeeeefff";
String[] tokens = text.split("(?<=\\G.{" + N + "})");
for(String t : tokens) {
System.out.println(t);
}
}
}

Sort a String array, whose strings represent int

I have String[] array like
{"3","2","4","10","11","6","5","8","9","7"}
I want to sort it in numerical order, not in alphabetical order.
If I use
Arrays.sort(myarray);
I obtain
{"10","11","2","3","4","5","6","7","8","9"}
instead of
{"2","3","4","5","6","7","8","9","10","11"}
Try a custom Comparator, like this:
Arrays.sort(myarray, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return Integer.valueOf(o1).compareTo(Integer.valueOf(o2));
}
});
Hope you like it!
I think by far the easiest and most efficient way it to convert the Strings to ints:
int[] myIntArray = new int[myarray.length];
for (int i = 0; i < myarray.length; i++) {
myIntArray[i] = Integer.parseInt(myarray[i]);
}
And then sort the integer array. If you really need to, you can always convert back afterwards:
for (int i = 0; i < myIntArray.length; i++) {
myarray[i] = "" + myIntArray[i];
}
An alternative method would be to use the Comparator interface to dictate exactly how elements are compared, but that would probably amount to converting each String value to an int anyway - making the above approach much more efficient.
I found this article about sorting strings by numeric sorting also for strings that may or may not contain numbers:
The Alphanum Algorithm
There is a Java implementation example linked from the article.
With that class you should be able to sort your arrays numerically like this:
Arrays.sort(myarray, new AlphanumComparator());
U can use sol-1 if it contains only numbers in string format.
Solution-1: -
String []arr = {"3","2","4","10","11","6","5","8","9","7"};
Set<Integer> set = new TreeSet<Integer>();
Arrays.sort(arr);
for(String s:arr){
System.out.print(s+" ");
set.add(Integer.parseInt(s));
}
System.out.println(set);
Integer i = new Integer("4f");
System.out.println(i);
Solution-2:-
String []arr = {"3","2","4","10","11","6","5","8","9","7","jgj","ek"};
Set<Integer> intSet = new TreeSet<Integer>();
Set<String> strSet = new TreeSet<String>();
Arrays.sort(arr);
for(String s:arr){
try {
int i = Integer.parseInt(s);
intSet.add(i);
} catch (NumberFormatException e) {
strSet.add(s);
}
}
List<String> result = new ArrayList<String>();
for(int val:intSet){
result.add(val+"");
}
result.addAll(strSet);
System.out.println(result);
}
Solution-3:-
Write one CustomComparator class and pass it to the sort() method.
public class CustomComparator implements Comparator<String>{
#Override
public int compare(String s1, String s2) {
Integer i1=null;
Integer i2=null;
try {
i1 = Integer.parseInt(s1);
} catch (NumberFormatException e) {
}
try {
i2 = Integer.parseInt(s2);
} catch (NumberFormatException e) {
}
if(i1!=null && i2!=null){
return i1.compareTo(i2);
}else{
return s1.compareTo(s2);
}
}
}
public static void main(){
String []arr = {"3","2","4","10","11","6","5","8","9","7","jgj","ek"};
Arrays.sort(arr, new CustomComparator());
for(String s:arr){
System.out.print(s+" ");
}
}
If all elements if your String array represent numbers, and if the numbers are always positive, then there is a simple way to sort numerically without a limit to the value of the number.
This is based on the fact that a number with a larger number of digits is, in that case, always higher than a number with a smaller number of digits.
You first compare the number of digits, and then (only if the number of digits is the same) you compare the value alphabetically:
Arrays.sort(array,
Comparator.comparing(String::length).thenComparing(Function.identity()));
in jdk8, you can write this code with lambda.
List<String> list = Arrays.asList("3", "2", "4", "10", "11", "6", "5", "8", "9", "7");
list.sort(Comparator.comparingInt(Integer::valueOf));
list.forEach(System.out::println);
especially such as input
String[]{"3.b", "2.c", "4.d", "10.u", "11.a", "6.p", "5.i", "8.t", "9.e", "7.i"}
you can use string.subString to chose which value is you really want to sort.
like
files.sort(Comparator.comparingInt(a -> Integer.valueOf(a.substring(0, a.indexOf(".")))));
Your desired output contains the numerical order of corresponding integers of your strings. So simply you cannot avoid conversion of strings to integers. As an alternative comparator to vikingsteve's you can use this:
Arrays.sort(array, new Comparator<String>() {
#Override
public int compare(String str1, String str2) {
return Integer.parseInt(str1) - Integer.parseInt(str2);
}
});
public class test1 {
public static void main(String[] args)
{
String[] str = {"3","2","4","10","11","6","5","8","9","7"};
int[] a = new int[str.length];
for(int i=0;i<a.length;i++)
{
a[i]=Integer.parseInt(str[i]);
}
Arrays.sort(a);
for(int i=0;i<a.length;i++)
{
str[i]=String.valueOf(a[i]);
}
}
}
This is the best solution I could come with, we can't convert to integer when the string is huge, this method sort an array of strings
public static void sortListOfStringsAsNumbers(List<String> unsorted) {
String min = "";
for (int i = 0; i < unsorted.size(); i++){
min = unsorted.get(i);
int indexMin = i;
for (int j = i + 1; j < unsorted.size(); j++){
if (unsorted.get(j).length() < min.length()){
min = unsorted.get(j);
indexMin = j;
}else if (unsorted.get(j).length() == min.length()){
for (int x = 0; x < unsorted.get(j).length(); x ++){
if (unsorted.get(j).charAt(x) < min.charAt(x)){
min = unsorted.get(j);
indexMin = j;
}else if (unsorted.get(j).charAt(x) > min.charAt(x)){
break;
}
}
}
}
if (indexMin != i){
String temp = unsorted.get(i);
unsorted.set(i, min);
unsorted.set(indexMin, temp);
}
}
}
All the solutions are for only integer numbers. what if the array contains floating numbers as well?
Here is the best solution which allows you to sort any type of value in the string.
import java.math.BigDecimal;
import java.util.*;
class Sort
{
public static void main(String...arg)
{
String s[]={"-100","50","0","56.6","90","0.12",".12","02.34","000.000"};
System.out.println("\n"+Arrays.toString(s)); //print before sorting
Arrays.sort(s, new Comparator<String>() {
public int compare(String a1, String a2) {
BigDecimal a = new BigDecimal(a1);
BigDecimal b = new BigDecimal(a2);
return a.compareTo(b);
}
});
System.out.println("\n"+Arrays.toString(s)); //print after sorting
}
}

Sorting String[][] unexpected output

I want to sort my String[][] with respect to second column. I tried this
public static String[][] sorting_minn(String[][] list){
double[] temp = new double[list.length];
String[][] tempf = list;
if(list[1][1]!=null){
for(int i = 0; i<list.length; i++){
if(list[i][2]==null){
break;
} else {
temp[i]=Double.parseDouble(list[i][2]);
}
}
Arrays.sort(temp);
for(int f = 0; f<list.length-1;f++){
for(int m = 0; m<list.length;m++){
if(list[m][2]!=null && Double.parseDouble(list[m][2])==temp[f]){
for(int n = 0; n<4; n++){
tempf[list.length-f-1][n]=list[m][n];
}
m = list.length;
}
}
}
}
return tempf;
}
As an output I get this: . I need suggestion on how to improve this code.
try something like:
Arrays.sort(list, new Comparator<String[]>() {
#Override
public int compare(String[] o1, String[] o2) {
String left = o1[1]!=null ? o1[1] : "";
String right = o2[1]!=null ? o2[1] : "";
return left.compareTo(right);
}
});
this treats nulls as empty strings, and exploits the fact that strings are comparable, although lexicographic. if you want the reverse order just do this instead:
right.compareTo(left)
if you want integer ordering you could parse an Integer out of both sides (Integer.MIN for null) and compare 2 Integers

java delete reverse string in list

I have struct Array or List String like:
{ "A.B", "B.A", "A.C", "C.A" }
and I want delete reverse string from list that end of only:
{ "A.B", "A.C" }
how type String use and how delete reverse String?
To reverse a string I recommend using a StringBuffer.
String sample = "ABC";
String reversed_sample = new StringBuffer(sample).reverse().toString();
To delete object form you ArrayList use the remove method.
String sample = "ABC";String to_remove = "ADS";
ArrayList<String> list = new ArrayList<Sample>();
list.add(to_remove);list.add(sample );
list.remove(to_remove);
You can get use of a HashMap to determine whether a string is a reversed version of the other strings in the list. And you will also need a utility function for reversing a given string. Take a look at this snippets:
String[] input = { "A.B", "B.A", "A.C", "C.A" };
HashMap<String, String> map = new HashMap<String, String>();
String[] output = new String[input.length];
int index = 0;
for (int i = 0; i < input.length; i++) {
if (!map.containsKey(input[i])) {
map.put(reverse(input[i]), "default");
output[index++] = input[i];
}
}
A sample String-reversing method could be like this:
public static String reverse(String str) {
String output = "";
int size = str.length();
for (int i = size - 1; i >= 0; i--)
output += str.charAt(i) + "";
return output;
}
Output:
The output array will contain these elements => [A.B, A.C, null, null]
A code is worth thousand words.....
public class Tes {
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
arr.add("A.B");
arr.add("B.A");
arr.add("A.C");
arr.add("C.A");
System.out.println(arr);
for (int i = 0; i < arr.size(); i++) {
StringBuilder str = new StringBuilder(arr.get(i));
String revStr = str.reverse().toString();
if (arr.contains(revStr)) {
arr.remove(i);
}
}
System.out.println(arr);
}
}
You can do this very simply in O(n^2) time. Psuedocode:
For every element1 in the list:
For every element2 in the list after element1:
if reverse(element2).equals(element1)
list.remove(element2)
In order to make your life easier and prevent ConcurrentModificationException use Iterator. I won't give you the code because it's a good example to learn how to properly use iterators in Java.
Reverse method:
public String reverse(String toReverse) {
return new StringBuilder(toReverse).reverse().toString();
}
Edit: another reverse method:
public String reverse(String toReverse) {
if (toReverse != null && !toReverse.isEmpty) {
String[] elems = toReverse.split(".");
}
StringBuilder reversedString = new StringBuilder("");
for (int i = elems.length - 1; i >= 0; i++) {
reversedString.append(elems[i]);
reversedString.append(".");
}
return reversedString.toString();
}
Check this
public static void main(String arg[]){
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
List<String> strList = new ArrayList<String>();
strList.add("A.B");
strList.add("B.A");
strList.add("A.C");
strList.add("C.A");
Iterator<String> itr = strList.iterator();
while(itr.hasNext()){
String [] split = itr.next().toUpperCase().split("\\.");
if(str.indexOf(split[0])>str.indexOf(split[1])){
itr.remove();
}
}
System.out.println(strList);
}
output is
[A.B, A.C]
You can iterate the list while maintaining a Set<String> of elements in it.
While you do it - create a new list (which will be the output) and:
if (!set.contains(current.reverse())) {
outputList.append(current)
set.add(current)
}
This solution is O(n*|S|) on average, where n is the number of elements and |S| is the average string length.
Java Code:
private static String reverse(String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length()-1 ; i >=0 ; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
private static List<String> removeReverses(List<String> arr) {
Set<String> set = new HashSet<String>();
List<String> res = new ArrayList<String>();
for (String s : arr) {
if (!set.contains(reverse(s))) {
res.add(s);
set.add(s);
}
}
return res;
}
public static void main(String[]args){
String[] arr = { "a.c" , "b.c", "c.a", "c.b" };
System.out.println(removeReverses(arr));
}
will yield:
[a.c, b.c]

Categories