C# 与 JAVA 常见代码对照表

# 功能表述 JAVA C# 差异点
1 新建List

List list =Lists.newArrayList();

List list =Lists.newLinkedList();

List list = new List();

在C#中,List只有一种实现,即List

java则有多种

2 新建Map Map map = Maps.newHashMap();  Dictionary dict = new Dictionary();

在C#中,Map使用Dictionary来实现,

java则有多种

3 循环List

for (String s : list) {

    System.out.println(s);

}

foreach (string s in list) {

    Console.WriteLine(s);

}

4 循环Map

for (Map.Entry entry : map.entrySet()) {

    System.out.println(entry.getKey() + ": " + entry.getValue());

}

foreach (KeyValuePair kvp in dict) {

    Console.WriteLine(kvp.Key + ": " + kvp.Value);

}

5 foreach list.forEach(item -> System.out.println(item)); list.ForEach(item => Console.WriteLine(item));
6

以对象的某个属性为key,另一属性为value,转Map

Map map = peopleList.stream()

    .collect(Collectors.toMap(Person::getName, Person::getAge));

Dictionary map = peopleList.ToDictionary(t => t.Name,t => t.Age);

java:  key重复,后来者取而代之

c#: 报错

7 以对象的某个属性为key,自身为value,转Map

Map map = peopleList.stream()

    .collect(Collectors.toMap(Person::getName, Function.identity()));

Dictionary map= peopleList.ToDictionary(t => t.Name);

java:  key重复,后来者取而代之

c#: 报错

8 给对象中某属性重新赋值

peopleList.stream()

    .map(person -> 

{ person.setAge(person.getAge() + 10);

        return person;

})

    .collect(Collectors.toList());

peopleList= peopleList.Select(

                person => {

                        x.age= x.age + 10;

                        return person;

                }).ToList();

9 对对象列表以某条件进行过滤

List result = list.stream()

    .filter(i -> i % 2 == 0)

    .collect(Collectors.toList());

List result = list.Where(i => i % 2 == 0).ToList();

10 对对象列表进行分组并转为Map

Map> ageGroups = persons.stream()

    .collect(Collectors.groupingBy(Person::getAge));

Dictionary> map ageGroups = persons.GroupBy(p => p.Age).ToDictionary(g => g.Key, g => g.ToList());

11 对对象列表根据某属性进行排序

List sortedPersons = persons.stream()

.sorted(Comparator.comparing(Person::getAge))

    .collect(Collectors.toList());

ListsortedPersons = persons.OrderBy(p => p.Age);
12 对对象列表根据某属性去重

List distinctPersons = persons.stream().collect(

        Collectors.collectingAndThen(

                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Person::getId))),

                ArrayList::new));

var distinctPersons = persons.GroupBy(p => p.Id).Select(g => g.First()).ToList();

你可能感兴趣的:(java,c#,开发语言)