简体   繁体   中英

Sort specific parts in String

Alright so, I have a String which contains: 1 456 2 100 3 600 1 400

The 1 is the Id of a person which got a score of 456 and 400. 2 is the Id of a person which got a score of 100 etc.

I need the String to sort by values and not by id's . It should look like this: 2 100 1 400 1 456 3 600

I already tried putting it into a hashmap and sorting it, but since a hashmap doesn't take identical keys, this is not an option.

Here is the full snippet , but as WJS commented , create a class:

public class Person {
    private String id;
    private int score;
    ...
}

Then add these to a List:

...
String[] parts = s.split(" ");
    
List<Person> people = new ArrayList<>();
for (int i = 0; i < parts.length; i += 2) {
    String id = parts[i];
    int score = Integer.parseInt(parts[i+1]);
    people.add(new Person(id, score));
}

Then you sort the list by passing a comparator which compares scores and if you need it back in a String, join the list with spaces:

people.sort((p1, p2) -> Integer.compare(p1.score, p2.score));    
String result = people.stream().map(Person::toString).collect(Collectors.joining(","));

Ok, here is how I did it. I used a record instead of a class as it creates the getters implicitly. No setters since a record is immutable.

record and data string

record Data (int id, int score) {
  @Override
  public String toString() {
      return"id=%d, score=%d".formatted(id, score);
  }
}
String data = "1 456 2 100 3 600 1 400";
  • create the list to hold the data
  • split on one or more white space characters
  • then for each (id, score) pair , create an instance of Data (I converted both to ints)
  • add the instance to the list
  • and sort the list
List<Data> list = new ArrayList<>();
String[] items = data.split("\\s+");
for(int i = 0; i < items.length; i+=2) {
    list.add(new Data(Integer.parseInt(items[i]), Integer.parseInt(items[i+1])));
}
list.sort(Comparator.comparingInt(Data::value));
for (Data d : list) {
    System.out.println(d);
}

prints

id=2, score=100
id=1, score=400
id=1, score=456
id=3, score=600


The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM